I created a file called foo bar (with the command touch foo\ bar).
Then, in Bash I tried the following commands:
s='"foo bar"'; find $s
s='"foo bar"'; find "$s"
s="foo bar"; find "$s"
With the first one, find looks for files named "foo and then for files named bar".
With the second one, find looks for files named "foo bar".
Both commands fail: find does not find any file.
Finally the third command has the expected behaviour: find looks for foo bar and shows it.
I know it is bad practice not to escape the space character, but can anyone explain me what is going on here? Why doesn't the second command work?
Because you are looking for something called
"foo bar". You quoted too much :)By saying:
you indicate that the variable
$sis in fact"foo bar". That is, the quotes belong in the variable content.When you say:
you are trying to find those files whose name is exactly
"foo bar", with the quotes. Then, if we create a file with this exactly name, it will work:When you say:
You are in fact saying:
That is, you are using
findtogether with two arguments:"fooorbar". And neither of these files exist. But, again, if you create one of them, voilà!Note the behaviour of
find X Yis to look forXandY: