Bash Shell命令在放入函数时停止创建文件

pgccezyw  于 2023-03-24  发布在  Shell
关注(0)|答案(1)|浏览(105)

下面的代码是使用grep查找文件,然后将其复制到一个新文件夹中,并使用新名称(found_file1 found_file2等)。
当search(){...}被删除并且程序按原样运行时,它可以工作。但是当放入一个函数时,它会删除-创建Found文件夹,但无法在其中创建文件。

#!/bin/bash

search(){

founddir=$(pwd)/Found

#---------gets inputs
echo "Enter the name of the directory:"
read searchdir
echo "Enter the keyword: "
read keyword

#-----this if statement checks if there are matching files
if grep -q -lr $keyword "$(pwd)/$searchdir"
then

    rm -rf Found 
    #removes old Found file, we're running this over and over it becomes more convinient to automate it this way. will be removed later
    mkdir Found 
#creates found file folder

    grep -q -lr $keyword "$(pwd)/$searchdir" | while read -r dir ; do 
        #------creates filepath to use in touch command, UNCERTAIN if it manages to
        file="$founddir/found_$(basename $dir)"
    enter code here
        #should create a file but does not
        touch $file

        #cant cp contents because file is not created
        cp -p $dir $file

    done

    echo "Files were copied to the Found directory!"

else
echo "Keyword not found in files!"
fi

}
search

我们已经尝试在变量声明中添加/删除引号,但似乎没有帮助。

z18hc3ub

z18hc3ub1#

我不确定你的函数应该做什么,但我认为你的问题在这一行:

grep -q -lr $keyword "$(pwd)/$searchdir" | while read -r dir ; do

-q不返回任何东西,但退出代码.所以在这种情况下,当你管道输出grepwhile循环,有什么while做.
你可能需要做的是从grep中删除-q,这样它将返回while的文件名,以便在循环中设置dir变量,然后完成其余的工作。

相关问题