Bash: IF shorthand

We all know how to make an if then else decision in programming or scripting languages. In bash , and most other languages it is possible to reduce several lines of code to a one-liners. Lets call that short-hand.

A typical if then else

if [ $num -eq 4 ] 
then
    echo "variable num equals 4"
else
    echo "variable num contains a different value"
fi

This can also written down in short-hand. The basic construct is [[ test ]] && actions_if_true || action_if_false

The code looks like this;

[[ $num -eq 4 ]] && echo "variable num equals 4" || echo "variable num contains a different value"

This entry was posted in CCNP and tagged . Bookmark the permalink.