if runs a command and reads its exit code: 0 runs the then lines, anything else the else lines. Chapter 1's if [ -d "$1" ] ran the command [, but any command works:
bash
#!/bin/bash
# Usage: bake.sh
if grep -q "oven on" ~/logs/oven.log; then
echo "baking"
else
echo "nobody turned the oven on"
exit 1
fitext
learner@reef:~$ ./bake.sh
nobody turned the oven on ← grep found no line: code 1, so the else lines ran
learner@reef:~$ echo $?
1Write ~/check-log.sh LOG:
| The log | It prints | Exit code |
|---|---|---|
has an ERROR line | problems in LOG | 1 |
| has none | LOG is clean | 0 |
-
Write it with
nano ~/check-log.sh. Use"$1"for the log. -
Make it runnable and try it:
textlearner@reef:~$ chmod u+x ~/check-log.sh learner@reef:~$ ./check-log.sh logs/register.log problems in logs/register.log learner@reef:~$ echo $? 1 -
Try
logs/door.logtoo.
Objectives
- A log with an
ERRORline:problems in LOG, exit code 1. - A log without one:
LOG is clean, exit code 0.