I am using CentOS 6.4 final in two machines. I am executing a script.
The script contains the find command
path=$1
searchstring=$2
echo `find $path -name $searchString`
for filename in `find $path -name $searchString`
do
echo "$filename"
echo
done
./findfiles.sh /var/log/ *.txt
The above script is executing fine and printing the files. But in the second machine I am getting usage error: find: paths must precede expression
The reason behind is *.txt which got expanded in find command.After changing
for filename in find $path -name "$searchString"
it is executing fine.
Why syntax error is not happening in first CentOS machine?
Quote your shell arguments:
$ ./findfiles.sh /var/log/ '*.txt'
You need to use proper quoting or the shell will try to expand *.txt before find sees it.
So if the current folder contains a.txt and b.txt, then find /var/log -name a.txt b.txt will be executed -> find will be confused what you want to do with b.txt
That's why it's so important to use proper quoting. Your script should be:
path="$1"
searchstring="$2"
echo $(find "$path" -name "$searchString")
for filename in $(find "$path" -name "$searchString")
do
echo "$filename"
echo
done
Note that I've quotes variable assignments (otherwise, the glob expansion will happen when you define searchstring. Same when you use the variables.
No quotes around $()! If you would add quotes there, then find would return a single "word" as result.
Also always prefer $() over the old inline-eval with back-ticks. It's much more reliable, less prone to subtle errors and more readable.