Conditions
- If any command runs successfully inside if conditional expression then if treats it as true.
if print; then echo "foo"; else echo "bar"; fi
- There's a command called
testto evaluate conditional expression.
if test $a -ge $b;
then
echo "a is bigger";
else
echo "b is bigger";
fi
see the test command ? It evaluates the conditional expression and return true / false based on the evaluation.
testis later replaced with[.
if [ $a -ge $b ];
then
echo "a is big";
else
echo "b is big";
fi
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.
- There's some limitations of using
[ortest. 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
You can also read more about the differences between [ and [[ from here.
- There's no ternary operator in bash. But there's a hack ...
[[ $a == $b ]] && echo "Equal" || echo "Not equal"
- One Liner
if [ -d "/var/www/html/" ]; then echo "html Directory exists"; else echo "html Directory not exist "; fi