I am trying to write a script that is looking for a directory for files and greps for a template. Something similar to the following except find is much more complex (excluding certain directories and files).
#!/bin/bash if [ -d "${!#}" ] then path=${!#} else path="." fi find $path -print0 | xargs -0 grep "$@"
Obviously this does not work, because "$@" still contains the path. I tried the options for creating an argument list, iterating over all arguments to exclude the path, e.g.
args=${@%$path} find $path -print0 | xargs -0 grep "$path"
or
whitespace="[[:space:]]" args="" for i in "${@%$path}" do # handle the NULL case if [ ! "$i" ] then continue # quote any arguments containing white-space elif [[ $i =~ $whitespace ]] then args="$args \"$i\"" else args="$args $i" fi done find $path -print0 | xargs -0 grep --color "$args"
but they do not work with the specified input. For example,
# ./find.sh -i "some quoted string" grep: quoted: No such file or directory grep: string: No such file or directory
Note that if $@ does not contain a path, the first script does what I want.
EDIT : Thanks for the great solutions! I went with a combination of answers:
#!/bin/bash path="." end=$# if [ -d "${!#}" ] then path="${!#}" end=$((end - 1)) fi find "$path" -print0 | xargs -0 grep "${@:1:$end}"
bash shell arguments
ctuffli
source share