Searching for a file in a directory, using bash script
[ $i = "*f*" ]
splits the file name stored in the variable i
into separate words at spaces, interprets each word as a wildcard pattern and expands it if it matches, and then parses the resulting list of words as a condition for [ … ]
. To avoid this rigmarole and instead use the file name, put double quotes around the variable expansion.
[ "$i" = "*f*" ]
tests whether the file name in the variable i
is the three-character name *f*
. If you don't have a file with this name, then all files will trigger the else branch, so yes
is printed.
In ksh, bash or zsh, you can test whether a string matches a wildcard pattern by using the double bracket construct. Leave the wildcards in the pattern unquoted.
if [[ "$i" = *f* ]]; then …
In plain sh, there is no double bracket syntax. To test whether a string matches a pattern, you can use a case
construct.
case "$i" in
*f*) echo "no";;
*) echo "yes";;
esac