Search code examples
linuxbashksh

bash/ksh grep script take more than one argument


   #!/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


Solution

  • 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).