Hugo Slop
Hugo Slop

Reputation: 11

Complicated if-then-else statement

So, I simplified this code. Every time it runs, else or $msg4 is always executed. How do I change it so it only does else if the $nick part doesn't match?

if [ "$who" = "$nick1" ]
    then echo $msg1
fi   
if [ "$who" = "$nick2" ] 
    then echo $msg2
fi  
if [ "$who" = "$nick3" ] 
    then echo $msg3   
else $msg4 
fi   

Upvotes: 0

Views: 60

Answers (2)

Walter A
Walter A

Reputation: 20012

Use case .. esac

case "$who" in
"$nick1") echo "$msg1";;
"$nick2") echo "$msg2";;
"$nick3") echo "$msg3";;
*)        echo "$msg4";;
esac

Upvotes: 1

Jonas Berlin
Jonas Berlin

Reputation: 3482

Here you can read how Bash if statements work: https://www.gnu.org/software/bash/manual/html_node/Conditional-Constructs.html#Conditional-Constructs

There you can see there is an elif which you should use to chain multiple if - else things together so that the final else is only executed if none of the if statements match. Result:

if [ "$who" = "$nick1" ]
then
    echo $msg1
elif [ "$who" = "$nick2" ]
then
    echo $msg2
elif [ "$who" = "$nick3" ]
then
    echo $msg3
else
    echo $msg4
fi 

You can also write the then on the same line as if if you add a ; before then:

if [ "$who" = "$nick1" ]; then
    echo $msg1
elif [ "$who" = "$nick2" ]; then
    echo $msg2
elif [ "$who" = "$nick3" ]; then
    echo $msg3
else
    echo $msg4
fi 

This is often easier to read.

Upvotes: 2

Related Questions