From 958a931dc84212410934b2670bc5cc9ba5185a30 Mon Sep 17 00:00:00 2001 From: koalaman Date: Sun, 28 Aug 2016 20:27:25 -0700 Subject: [PATCH] Created SC2181 (markdown) --- SC2181.md | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 SC2181.md diff --git a/SC2181.md b/SC2181.md new file mode 100644 index 0000000..d98986c --- /dev/null +++ b/SC2181.md @@ -0,0 +1,35 @@ +## Check exit code directly with e.g. 'if mycmd;', not indirectly with $?. + +### Problematic code: + +```sh +make mytarget +if [ $? -ne 0 ] +then + echo "Build failed" +fi +``` + +### Correct code: + +```sh +if ! make mytarget +then + echo "Build failed" +fi +``` +### Rationale: + +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. + +To check that a command returns success, use `if mycommand; then ...`. + +To check that a command returns failure, use `if ! mycommand; then ...`. + +This also applies to `while`/`until` loops. + +### Exceptions: + +None. \ No newline at end of file