dimanche 6 décembre 2015

Bash function with grep, using if and then statements

I have been trying to build a function that will allow me to perform a dynamic grep search - dynamic in that if more than one variable is specified upon calling the function, then it will pass the additional variable through grep. I should never really need more than 2 variables, but would be interested in learning how to do that as well.

example of desired functionality:

shell#function word1 word2

result: ( cd /path/folder; less staticfile | grep -i word1 | grep -i --color word2 )`

The above works great if there will always be two words. i'm trying to learn how to use if and then statements to allow me to be flexible in the number of variables.

function () { if [ ! "$#" -gt "1" ]; then ( cd ~/path/folder; less staticfile | grep -i $1 | grep --color -i $2 ) else ( cd ~/path/folder; less staticfile | grep --color $1 ) fi

When I run this function, it seems to do the opposite -

shell# function word1

returns an error because it is using the "then" statement for some reason but has nothing to insert into the second grep call.

shell# function word1 word2

only greps "word1" - therefore is using the "else" statement. What am i doing wrong? Is there any easier way to do this?

Aucun commentaire:

Enregistrer un commentaire