5.1 Conditionals
The if [..] .. then .. else .. fi statement
This construction allows to execute commands conditional on the evaluation of other expressions. They are to be written on different lines or separated by semicolons (;).
Declaring variables from output
if [ "foo" = "foo" ]; then echo "true!"; fi
#true!
if [ 1 > 20 ]; then echo "true!"; else echo "false!"; fi
#true!
if [ 1 -gt 20 ]; then echo "true!"; else echo "false!"; fi
#false!By default, the expression is evaluating the arguments as strings. To force a numerical evaluation, -lt (<), -gt (>), -le (<=), -ge (>=), -eq (==) or -ne (!=).
File test operators
BASH offers built-in tests for the status of files.
The most important are:
- -e tests if a file / directory exists
- -f tests if it is a regular file (no directory)
- -d tests if it is a directory
- -s tests if the size of a file is > zero
File test operators
if [ -f out.txt ]; then echo "true"; else echo "false"; fi
#true
if [ -d out.txt ]; then echo "true!"; else echo "false"; fi
#false!Testing for not
To test for the opposite, simply put an exclamation mark ! before the operator.
File test operators