DEV Community

Rafaf Tahsin
Rafaf Tahsin

Posted on

bash conditions

  1. If any command runs successfully inside if conditional expression then if treats it as true.
if print; then echo "foo"; else echo "bar"; fi
Enter fullscreen mode Exit fullscreen mode

2 There's a command called test to evaluate conditional expression.

if test $a -ge $b; 
then 
    echo "a is bigger"; 
else 
    echo "b is bigger"; 
fi
Enter fullscreen mode Exit fullscreen mode

see the test command ? It evaluates the conditional expression and return true / false base on the evaluation.

  1. test is later replaced with [.
if [ $a -ge $b ]; 
then 
    echo "a is big"; 
else 
    echo "b is big"; 
fi
Enter fullscreen mode Exit fullscreen mode

Yes, the command is [ and it starts evaluating the expression until it gets ]. You can check it yourself with which [ or even man [. [ is basically another representation of test command.

  1. There's some limitations of using [ or test. For example, it can't evaluate &&, ||. So here comes [[ with improvements.
if [[ $a > $b || $a == $b ]]; then echo "a is big"; else echo "b is big"; fi
Enter fullscreen mode Exit fullscreen mode

You can also read more about the differences between [ and [[ from here.

  1. There's no ternary operator. But there's a hack ...
[[ $a == $b ]] && echo "Equal" || echo "Not equal"
Enter fullscreen mode Exit fullscreen mode

Top comments (0)