Paul
Paul

Reputation: 321

How to avoid multiple OR statement bash

I have GUI check list for parameters to use grep search. When you check the list - this parameter should show up in grep control option.

For example:

w=TRUE or FALSE
s=TRUE or FALSE
N=TRUE or FALSE
L=TRUE or FALSE

And I would like to use all combination of check list selection something like:

if [ "$w" == TRUE ]; then

grep -w searsch_pattern INFILE


elif [ "$w" == TRUE ] && [ "$s" == TRUE ];then

grep -w -s searsch_pattern INFILE

....

fi

My question is if possible to avoid write all combination elif statement and found some more elegant solution.

PS: I want to use more then four output control parameters in grep search.

Thank you for any help.

Upvotes: 0

Views: 63

Answers (2)

SLePort
SLePort

Reputation: 15461

For single options as in your example, you can try :

w=TRUE 
s=TRUE
N=FALSE
L=TRUE

for opt in w s N L; do
  [[ ${!opt} == "TRUE" ]] && options+=" -${opt}"
done

grep "${options}" searchpattern INFILE

Upvotes: 1

chepner
chepner

Reputation: 531908

Generally, no, unless the effects of each flag are independent. You could try building up the arguments to grep in an array. For example:

grep_options=()
if [ $w == TRUE ]; then
    grep_options+=( -w  )
fi

if [[ $s == TRUE ]]; then
    grep_options+=(-s)
fi

# etc.

grep "${grep_options[@]}" search_pattern INFILE

Upvotes: 3

Related Questions