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 like 'if'. [ -f ] means 'if the file exists'. then means 'then do'. fi closes the block — it's if backwards. [ ] is a command — 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.