user3915191
user3915191

Reputation: 53

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

Upvotes: 3

Views: 3647

Answers (2)

Arman
Arman

Reputation: 25

I usually do this way -->

#!/bin/bash
dir=$1
file="*$2*"
find $dir -iname $file -print

Upvotes: 0

Bjorn Munch
Bjorn Munch

Reputation: 496

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";

Upvotes: 2

Related Questions