[ ] compares text and numbers, with different tests:
| Test | True when |
|---|---|
[ "$a" = "$b" ] | The texts are the same (!=: they differ) |
[ -z "$a" ] | The text is empty |
[ "$a" -eq "$b" ] | The numbers are equal |
[ "$a" -lt "$b" ] | a is less than b (-le: or equal) |
[ "$a" -gt "$b" ] | a is greater than b (-ge: or equal) |
elif tries another test when the ones above were false:
#!/bin/bash
# Usage: fridge.sh DEGREES
if [ "$1" -gt 8 ]; then
echo "too warm"
elif [ "$1" -lt 1 ]; then
echo "too cold"
else
echo "ok"
filearner@reef:~$ ./fridge.sh 0
too cold ← 0 is not above 8, so elif tried the next testNumbers use -gt, not >. Inside [ ], > still sends output to a file.
Ben's ~/oven-check.sh asks the oven how hot it is. It should do this:
oven-status prints | oven-check.sh prints | Exit code |
|---|---|---|
a number up to 180 | heating: wait | 0 |
a number above 180 | ready: bake | 0 |
fault | fault: call the engineer | 1 |
-
See it go wrong:
textlearner@reef:~$ oven-status 90 learner@reef:~$ ./oven-check.sh ready: bake ← at 90 degrees!Run
ls: a new file called180. The>wrote it. -
Fix the test with
nano ~/oven-check.sh, thenrm ~/180. At 90 degrees, it says to wait. -
Add the
faultrow with=, above the number test:-gtcan't compare a word. Try it:textlearner@reef:~$ echo fault > /var/lib/oven/state learner@reef:~$ ./oven-check.sh
Objectives
- At 90 degrees, it says to wait.
- Above 180, it says to bake.
- On a fault, it says to call the engineer, and fails.