mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2181 (markdown)
35
SC2181.md
Normal file
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.
|
Reference in New Issue
Block a user