Created SC2181 (markdown)

koalaman
2016-08-28 20:27:25 -07:00
parent 02ffc404ec
commit 958a931dc8

35
SC2181.md Normal file

@@ -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.