if runs a command. Often, you want to check something: does this file exist? Are there two arguments? The command [ does checks.
text
learner@tidepool:~$ [ -f ~/prices.txt ]
learner@tidepool:~$ echo $?
0[ CHECK ] writes nothing. It ends with exit code 0 when the check is true, and 1 when it is false. That is exactly what if needs:
bash
if [ -f ~/prices.txt ]; then
echo "the price list is here"
fi[the command-f ~/prices.txtthe check]the last argument
Checks on files
| Check | True when |
|---|---|
[ -e PATH ] | The path exists |
[ -f PATH ] | It is a file |
[ -d PATH ] | It is a directory |
[ -x PATH ] | You can run it |
Checks on text and numbers
| Check | True when |
|---|---|
[ "$a" = "$b" ] | The texts are the same (!=: not the same) |
[ -z "$a" ] | The text is empty |
[ "$n" -eq 3 ] | The numbers are equal |
[ "$n" -gt 3 ] | n is greater than 3 (-lt: less than) |
Turn a check around: !
[ ! -f PATH ] is true when the file does not exist.
Check the arguments of a script
Stop early when a script gets the wrong number of arguments:
bash
if [ $# -ne 1 ]; then
echo "usage: check.sh FILE"
exit 2
fi-ne means "not equal".