bash 脚本中的间距有问题

Having an issue with spacing in bash script

我正在尝试以 find 命令作为条件来执行 if/else。由于目录中的间距,我遇到了错误。我在此处和 google 上进行了大量搜索,但无法解决此问题。提前感谢您的帮助。

我的代码:

#!/usr/bin/bash
dir="/to/Two Words/test/"
file="test.txt"

if [ `find $dir -name $file` ];
then
    echo "File $file is in $dir"
else
    echo "$file is not in $dir"
fi

结果:

find: ‘/to/Two’: No such file or directory
find: ‘Words/test/’: No such file or directory
test.txt is not in /to/Two Words/test/

由于空格,$dir 扩展为两个参数;添加引号以防止出现这种情况,find "$dir" ...

你必须double-quote$dir来避免这个词 splitting 但无论如何它是 不工作:

$ ./f.sh
./f.sh: line 5: [: space: binary operator expected

你想要:

#!/usr/bin/bash
dir="/to/Two Words/test/"
file="test.txt"

if [[ -n "$(find "$dir" -name "$file")" ]]
then
    echo "File $file is in $dir"
else
    echo "$file is not in $dir"
fi

if 不需要 [ 来执行命令,但是 find returns 0 即使没有找到文件。尝试使用带有 grep.

的管道
if find "$dir" -name "$file" | grep .

如果匹配失败,grep 将 return false。