spry
spry

Reputation: 393

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/

Upvotes: 0

Views: 248

Answers (3)

Milag
Milag

Reputation: 1996

Due to the whitespace, $dir expands to two args; add quotes to prevent that, find "$dir" ...

Upvotes: 0

Arkadiusz Drabczyk
Arkadiusz Drabczyk

Reputation: 12518

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

Upvotes: 2

Paul Hodges
Paul Hodges

Reputation: 15388

if does not require [ for command executions, but find returns 0 even if no files were located. Try using a pipeline with a grep.

if find "$dir" -name "$file" | grep .

The grep will return false if it fails a match.

Upvotes: 1

Related Questions