尝试将用户生成的变量传递给外部命令

尝试将用户生成的变量传递给外部命令

我有一个 bash 脚本,它要求用户输入,然后将该变量传递给 find 命令。我尝试过以我所知道的方式引用/转义变量,但它总是失败。

read -p "Please enter the directory # to check: " MYDIR
count=`/usr/bin/find /path/to/$MYDIR -name *.txt -mmin -60 | wc -l`
if [ $count != 0 ]
    then 
         echo "There have been $count txt files created in $MYDIR in the last hour"
    else 
         echo "There have been no txt files created in the last hour in $MYDIR "
    fi

运行时,我得到这个:

Please enter the directory # to check: temp_dir

/usr/bin/find: paths must precede expression
Usage: /usr/bin/find [-H] [-L] [-P] [path...] [expression]
There have been no txt files created in the last hour in temp_dir 

答案1

-name您必须在选项中引用模式:

count="$(/usr/bin/find /path/to/$MYDIR -name '*.txt' -mmin -60 | wc -l)"

如果不使用引号,那么 shell 将扩展该模式。你的命令变成:

/usr/bin/find "/path/to/$MYDIR" -name file1.txt file2.txt ... -mmin -60 | wc -l

.txt您提供名称以to选项结尾的所有文件-name。这会导致语法错误。

相关内容