Removing final bash script argument

Posted by ctuffli on Stack Overflow See other posts from Stack Overflow or by ctuffli
Published on 2010-03-16T22:01:29Z Indexed on 2010/03/16 22:11 UTC
Read the original article Hit count: 221

Filed under:
|
|

I'm trying to write a script that searches a directory for files and greps for a pattern. Something similar to the below except the find expression is much more complicated (excludes particular directories and files).

#!/bin/bash
if [ -d "${!#}" ]
then
    path=${!#}
else
    path="."
fi

find $path -print0 | xargs -0 grep "$@"

Obviously, the above doesn't work because "$@" still contains the path. I've tried variants of building up an argument list by iterating over all the arguments to exclude path such as

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 these fail with quoted 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 $@ doesn't contain the path, the first script does do what I want.

© Stack Overflow or respective owner

Related posts about bash

Related posts about shell-scripting