2

I'm making a bash shell script to find files with the star character in their name (*). My test directory has two files that match this criterion:

./File.With*In.It
./File.With*In.It copy

When I run the following command via Terminal on OS X, I get the aforementioned list above as my result:

find . -name '*\**'

But, in my shell script, I have the following line of code:

listOfStars=`find . -name '*\**'`
printf "%s\n" ${listOfStars}

And, if I execute the script, the result I get includes every file in the directory:

.
./File.With"In.It
./File.With"In.It copy
./File.With*In.It
./File.With*In.It copy
./File.With.In.It.
./File.With.In.It. copy.
./File.With:In.It
./File.With:In.It copy
./File.With<In.It
./File.With<In.It copy
./File.With>In.It
./File.With>In.It copy
./File.With?In.It
./File.With?In.It copy
./File.With\In.It
./File.With\In.It copy
./File.With|In.It
./File.With|In.It copy

On further testing, if I execute those two lines of code right in the Terminal, I also get the same results; every file in the directory matches the search. The obvious conclusion is that find - in the way I am using it - is giving me a different result when it's assigned to my variable than when I run the command all on its own.

What can I do to get find to behave in my variable the same way it does when summoned by itself? Or is there a more prudent approach to getting a list of files with star (*) in their names and assigning it to a variable in my bash shell script?

sivacrom
  • 35
  • 1
  • 7

1 Answers1

2

The find command is working correctly in both cases.
To avoid globbing during printing, surround your string with double quotes:

listOfStars=$(find . -name '*\**')
printf "%s\n" "${listOfStars}"
./File.With*In.It
./File.With*In.It copy
Eugeniu Rosca
  • 5,177
  • 16
  • 45
  • I can't believe I didn't try that. THANK YOU! This solved it thoroughly and elegantly. – sivacrom Jul 11 '15 at 23:54
  • 1
    And, what's more, this little nugget you tossed in: `listOfStars=$(find . -name '*\**')` as a reimagining of my example of `listOfStars=\`find . -name '*\**'\`` solved another problem I was having searching for files with backslashes in their names. Nicely done! – sivacrom Jul 12 '15 at 00:01
  • 1
    Command substitution (`$()`) is [prefered to using backticks](http://stackoverflow.com/questions/4708549/shell-programming-whats-the-difference-between-command-and-command). You're welcome. – Eugeniu Rosca Jul 12 '15 at 00:08