From e800a6eec4f4ca927f0f368a98bfc69e1fe5a0de Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 28 Aug 2016 21:19:56 -0700 Subject: [PATCH] Updated SC2181 (markdown) --- SC2181.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/SC2181.md b/SC2181.md index d98986c..3b04745 100644 --- a/SC2181.md +++ b/SC2181.md @@ -4,6 +4,7 @@ ```sh make mytarget + if [ $? -ne 0 ] then echo "Build failed" @@ -24,6 +25,12 @@ Running a command and then checking its exit status `$?` against 0 is redundant. Instead of just checking the exit code of a command, it checks the exit code of a command (e.g. `[`) that checks the exit code of a command. +Apart from the redundancy, there are other reasons to avoid this pattern: + +* Since the command and its status test are decoupled, inserting an innocent command like `echo "make finished"` after `make` will cause the `if` statement to silently start comparing `echo`'s status instead. +* Scripts that run or are called with `set -e ` aka `errexit` will exit immediately if the command fails, even though they're followed by a clause that handles failure. +* The value of `$?` is overwritten by `[`/`[[`, so you can't get the original value in the relevant then/else block (e.g. `if mycmd; then echo "Success"; else echo "Failed with $?"; fi`). + To check that a command returns success, use `if mycommand; then ...`. To check that a command returns failure, use `if ! mycommand; then ...`.