I have been trying to search for a file which contains a specific pattern. The pattern is itself in a variable tmpfl

echo $tmpfl --> ack_2*

Now to find for the file in the current working directory itself I have been trying to use

find . -name $tmpfl

find . -name ($tmpfl)

but none of them seem to work . Though

find . -name ack_2*

works like a charm .

What is wrong in the approach ? It's simple variable substitution in Unix , right ? So what am I missing ?


You need to put "" around your variable.

find . -name "$tmpfl"
  • I don't think that quoting matter here. Double quotes is used only when variable contains whitespaces. BTW, find -name $tmpfl works for me. – Arkadiusz Drabczyk Nov 24 '14 at 13:17
  • 1
    @ArkadiuszDrabczyk. No. double quote is used always. Leaving out the quotes is when you want the split+glob operator (nothing to do with spaces except for the split part if $IFS happens to contain space) to be invoked upon the expansion (in list contexts). In this case though, find . -name $tmpfl with the default value of IFS and tmpl containing act2_* would be equally wrong as find . -name act2_* as that glob would (could) be expanded in both cases. – Stéphane Chazelas Nov 24 '14 at 13:49

I have found there are certain situations (besides whitespace or unprintable characters) that require the double quotes around the -name parameter, regardless of whether the parameter is a variable or a hard-coded value. Always good to get in the habit of using them.

  • 1
    Leaving a variable expansion unquoted in list contexts in POSIX shells is the split+glob operator. Situations where you actually want that are very rare (and here is definitely not one), so variable expansions should generally be quoted. – Stéphane Chazelas Nov 24 '14 at 13:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.