Search code examples
bashif-statementscriptingfindquoting

Having an issue with spacing in bash script


I am trying to perform an if/else with the find command as the conditional. I am getting errors with because of the spacing in a directory. I have done a lot of searching on here and google and I'm unable to resolve this issue. Thank you for your help in advance.

My Code:

#!/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

The results:

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/

Solution

  • You have to double-quote $dir to avoid word splitting but anyway it's not going to work:

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

    You want:

    #!/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