Skip to content
Advertisement

bash script – executing find command gives no output

I’m a total noob at bash so this is most likely a syntax error, but I could not find anything that worked for my syntax in my searches.

From terminal, running
find . -name "*g*"
results in

./.grepdir.sh.swp  
./grepdir.sh

However, running this bash script called grepdir.sh

#!/usr/bin/bash
startdir="$1";
pattern="$2";
find_cmd="find $startdir -name "$pattern"";
echo "$find_cmd";

cmd="$($find_cmd)";
echo "$cmd";

from terminal as grepdir.sh . "*g*" results in:

[user@pc~/dir]$ grepdir.sh . "*g*"
find . -name "*g*"

[user@pc~/dir]$

meaning that cmd must be empty. But from my understanding, the string stored in find_cmd was executed and the output captured to cmd, meaning that it should not be empty. Do I have a misconception, or is my syntax just god-awful?

Thanks

Advertisement

Answer

The problem with your version of the script is that the quotes you add actually become part of the argument to find. So you ask it to search for file names that literally include "*g*" with quotes.

If you drop adding the quotes and just say find_cmd="find $startdir -name $pattern"; then it works for patterns not including special characters. Then I thought maybe this would work:

grepdir.sh . *g*

or even

grepdir.sh . \*g\*

but no. These things are always tricky….

Edit: A-ha, this version seems to work:

#!/usr/bin/bash
startdir="$1";
pattern="$2";
find_cmd="find $startdir -name $pattern";
echo "$find_cmd";

GLOBIGNORE=$pattern
cmd="$($find_cmd)";
echo "$cmd";
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement