user7214700
user7214700

Reputation:

grouping and simplifying multiple if conditions / bash

I have multiple If conditions to to run at the beginning of the script

if blah; then
echo "hop"
fi
if [ ! -f blah-blah ]; then
echo "hop-hop"
else
echo "hip-hop-hap"
fi
if [ $? -eq 0 ]; then
echo "hip-hop"
fi

each of this conditions are separate from each other, and I have them 7-8 so I'm thinking if there is some way to group them... I was thinking to use elif , but elif will stop checking conditions if one of them is truth, any suggestion would be ppreciated

Upvotes: 0

Views: 426

Answers (2)

Fred
Fred

Reputation: 6995

If what you are hoping for is shorter code, you could do something like this :

blah && echo "hop"
[ -f "blah-blah" ] && echo "hip-hop-hap" || echo "hop-hop"
[ $? = 0 ] && echo "hip-hop"

This is not "simpler" in the logical sense, but it is more concise.

Please note that I removed the ! from the test and switched the resulting statements as a small optimization.

Please note, however, that if you want to perform any kind of error checking or explicit handling (i.e. trap ... ERR, set -e), then using logical operators is going to interfere with that and you will not be able to tell the difference between a bug in your script and a command that fails for "good reasons" (i.e. attempting to delete a non-existing file). You are probably mostly safe if you restrict yourself to echo statements, or if, like most shell programmers, you allow the shell to simply ignore failed statements (which is not, in my opinion, a good way to build predictable and reliable shell code).

Upvotes: 1

Dima Chubarov
Dima Chubarov

Reputation: 17179

It is hard to give a definitive answer to a question that asks for some way.

Here is an alternative idea. We create an array of boolean values that contains the results of evaluation of logical conditions. And for each condition i define a pair of functions func${i}0 and func${i}1 that will be called when condition i evaluates to true or false respectively. Finally we loop through our boolean array.

The code below implements this idea. It is rather awkward. Feel free to suggest improvements or downvote.

Here we assume that blah evaluates to either 0 or 1.

# populate array b by evaluating boolean conditions 
foo=$( blah );                b[1]=$?
foo=$( [ ! -f blah-blah ] );  b[2]=$?
foo=$( [ $? -eq 0 ] );        b[3]=$?

# For each condition 1 through 3 define the actions when
# the condition is True or False
func10(){
echo "hop"
}
func11(){ :;}

func20(){
    echo "hop-hop"
}
func21(){
    echo "hip-hop-hap"
}

func30(){
    echo "hip-hop"
}
func31(){ :;}

#loop through the array and execute the functions 
for i in $(seq 1 ${#b[*]}) ; do
func${i}${b[i]}
done

Edits:

  1. Replaced {(:)} by { :;} per Charles Duffy suggestion
  2. The use of $(seq) in the loop is inefficient, yet explicitly incrementing the loop counter seems a bit too much to type.

Upvotes: 0

Related Questions