Lesson 20: Bash Conditionals
The script from the previous lesson creates a backup — but doesn't report whether it succeeded. We'll add an if condition to it. [ -f file ] tests file existence; [ -d dir ] tests directory existence; [ $? -eq 0 ] tests an exit code. [ is a real command — spaces are required before and after every a
if is simply 'if': [ -f ] asks 'does the file exist?', then means 'then', and fi closes the block — it's just if spelled backwards. One thing to remember: [ ] is a command in its own right, so it needs spaces around it like any command.
- bash if
- if [ condition ]; then ... fi. [ ] returns exit code 0 (true) or 1 (false). then opens the block body. fi (=if reversed) closes it. else on a separate line is valid for an alternative block.
- test operators
- -f: regular file exists. -d: directory exists. -e: path exists (any type). -eq: equal (numbers). -ne: not equal. -z: empty string. -n: non-empty string.