The exit code can decide what runs next.
| Line | Runs B |
|---|---|
A && B | Only when A worked (exit code 0) |
A || B | Only when A failed (any other code) |
A ; B | Always, after A |
A
exit code 0
B runs
A
any other code
B runs
grep -q: only the exit code
grep -q writes nothing. It only sets its exit code: 0 when a line matches, 1 when no line matches. That makes it good for checks:
text
learner@tidepool:~$ grep -q ERROR ~/logs/till.log && echo "look at the till log"
look at the till log
learner@tidepool:~$ grep -q juice ~/menu.txt || echo "juice is not on the menu"
juice is not on the menuBoth together
text
learner@tidepool:~$ grep -q ERROR ~/logs/till.log && echo "problems" || echo "all good"If grep finds a line, the first echo runs. If not, the second one runs.
Stop when a step fails
Join steps with && to stop at the first step that fails:
text
learner@tidepool:~$ mkdir -p ~/backup && cp ~/shop/prices.txt ~/backupIf mkdir fails, cp does not run.