Bash test and [ ]
test checks a condition and sets the exit status: 0 when it is true, 1 when it is false.
[ ] is the same command written another way. Put spaces inside the brackets: [ $a -gt 3 ].
Compare numbers
test 5 -gt 3 && echo "5 is greater"
5 is greater
[ 5 -lt 3 ]
echo $?
1
Check a file
[ -f notes.txt ] && echo "File exists"
File exists
[ -d notes.txt ] || echo "Not a folder"
Not a folder
Common Tests
| Test | True when |
|---|---|
-eq -ne -lt -le -gt -ge | Numbers are equal, not equal, less, less or equal, greater, greater or equal |
= != | Strings are equal, not equal |
-z -n | A string is empty, not empty |
-e -f -d | A path exists, is a file, is a folder |