Home > OS >  bash/ksh grep script take more than one argument
bash/ksh grep script take more than one argument

Time:04-23

   #!/bin/ksh
if [ -n "$1" ]
then
    if grep -w -- "$1" codelist.lst
    then
        true
    else
        echo "Value not Found"
    fi
else
    echo "Please enter a valid input"
fi

This is my script and it works exactly how I want at the moment, I want to add if I add more arguments It will give me the multiple outputs, How can I do that?

So For Example I do ./test.sh apple it will grep apple in codelist.lst and Give me the output : Apple

I want to do ./test.sh apple orange and will do: Apple Orange

CodePudding user response:

You can do that with shift and a loop, something like (works in both bash and ksh):

for ((i = $#; i > 0 ; i--)) ; do
    echo "Processing '$1'"
    shift
done

You'll notice I've also opted not to use the [[ -n "$1" ]] method as that would terminate the loop early with an empty string (such as with ./script.sh a b "" c stopping without doing c).

CodePudding user response:

To iterate over the positional parameters:

for pattern in "$@"; do
  grep -w -- "$pattern" codelist.lst || echo "'$pattern' not Found"
done

For a more advanced usage, which only invokes grep once, use the -f option with a shell process substitution:

grep -w -f <(printf '%s\n' "$@") codelist.lst
  • Related