How do I properly write a bash if else statement with elif?

I’m struggling to understand the correct syntax for a bash if else structure that includes elif. I’m trying to compare a string variable and execute different echo statements depending on its value.

Here’s what I’ve got:

aaa="xxx"
if [[ $aaa -eq "bbb" ]]; then
   echo "bbb"
elif [[ $aaa -eq "ccc" ]]; then
   echo "ccc"
else
   echo "something else"
fi

No matter what value I assign to aaa, it always prints “bbb”. I’ve tried variations with [ and [[, also switched between == and -eq, but nothing seems to work as expected. I’m clearly missing something in how bash if else syntax is supposed to work, especially with string comparisons. Can someone clarify what I’m doing wrong?

I’ve been working with Bash for quite some time, and one key thing I’ve learned is to always use == for string comparisons instead of -eq. The -eq operator is meant for numeric comparisons, and using it for strings leads to unexpected results. A quick fix is replacing -eq with == inside the double square brackets [[ ]]. Here’s a cleaner way to structure it:

aaa="xxx"
if [[ $aaa == "bbb" ]]; then
    echo "bbb"
elif [[ $aaa == "ccc" ]]; then
    echo "ccc"
else
    echo "something else"
fi

This way, Bash compares the actual string values correctly, and the weird mismatches you might have experienced will disappear. Simple yet effective!

Great point, @prynka.chatterjee! I’ve had a similar experience where my script was acting up because the variable had some hidden characters, like a trailing newline from a command substitution. It can be tricky, but here’s a quick way to check:

echo "Value is: [$aaa]"

This prints the variable with brackets around it, making it easy to spot any extra spaces or characters. Once you’ve cleaned up the variable, using == inside [[ ]] should work just fine, just like Priyanka showed.

Yes, and here’s another tip I’ve picked up over time: always quote your variables. This is a small step but prevents a lot of silent failures, especially when a variable is empty or contains special characters. Even though [[ ]] is lenient, quoting adds extra safety. Here’s how I’d write it:

if [[ "$aaa" == "bbb" ]]; then
    echo "bbb"
elif [[ "$aaa" == "ccc" ]]; then
    echo "ccc"
else
    echo "something else"
fi

By quoting the variable like "$aaa", you’re making sure that even if the variable is empty or has special characters, it won’t cause any parsing issues. This practice has saved me a lot of time debugging, so I always make it a habit now!