Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing final bash script argument

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.


EDIT : Thanks for the great solutions! I went with a combination of the answers:

#!/bin/bash

path="."
end=$#

if [ -d "${!#}" ]
then
    path="${!#}"
    end=$((end - 1))
fi

find "$path" -print0 | xargs -0 grep "${@:1:$end}"
like image 530
ctuffli Avatar asked Mar 16 '10 22:03

ctuffli


People also ask

How do you terminate a bash script?

One of the many known methods to exit a bash script while writing is the simple shortcut key, i.e., “Ctrl+X”. While at run time, you can exit the code using “Ctrl+Z”.

How do you remove the last character of a string in bash?

You can also use the sed command to remove the characters from the strings. In this method, the string is piped with the sed command and the regular expression is used to remove the last character where the (.) will match the single character and the $ matches any character present at the end of the string.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.


1 Answers

EDIT:

Original was just slightly off. No removal is to be done 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))}"
like image 183
Ignacio Vazquez-Abrams Avatar answered Oct 27 '22 01:10

Ignacio Vazquez-Abrams