Making Decisions
If and test.
A useful script needs to make choices. If the file exists, read it. If not, warn the user. In bash, choices are made with if, and a test inside square brackets.

- Scripts make choices
- File exists? Read it
- Otherwise, warn
check.sh
If, then a test in square brackets. Dash F asks, is this a normal file? If the test passes, bash runs the lines after then. Otherwise, it runs the lines after else. And FI, which is if backwards, ends the whole thing.
#!/bin/bash
file="$1"
if [ -f "$file" ]; then
echo "$file exists. It has $(wc -l < "$file") lines."
else
echo "Sorry, $file was not found."
fiBoth paths
Ask about notes dot TXT, and the test passes. It exists, with three lines. Ask about a file that isn't there, and the else part runs instead.
./check.sh notes.txt notes.txt exists. It has 3 lines. ./check.sh shopping.txt Sorry, shopping.txt was not found.
Common tests
Here are the tests you'll use most. Dash F for a file, dash D for a folder, dash Z for an empty string. For numbers, use dash EQ for equal, dash GT for greater than, and dash LT for less than. And always keep a space inside each square bracket. Bash is fussy about that.
| Test | True when |
|---|---|
| [ -f path ] | it's a file |
| [ -d path ] | it's a folder |
| [ -z "$x" ] | $x is empty |
| [ "$a" = "$b" ] | the text matches |
| [ "$n" -gt 5 ] | number greater than 5 |
Summary
If, a test in square brackets, then, else, and FI. Tests check files, text, and numbers. Next, more than two choices, with ELIF.
Key takeaways- if [ test ]; then … fi
- -f -d -z
- -eq -gt -lt