Removing the final argument to a bash script

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}" 
+7
bash shell arguments
source share
1 answer

EDIT:

The original was just slightly off. Do not delete if the last argument is not a directory.

 #!/bin/bash if [ -d "${!#}" ] then path="${!#}" remove=1 else path="." remove=0 fi find "$path" -print0 | xargs -0 grep "${@:1:$(($#-remove))}" 
+8
source share

All Articles