mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-03-12 12:35:25 -07:00
Created SC2320 (markdown)
parent
0c99f0bb02
commit
fe4f3036f9
40
SC2320.md
Normal file
40
SC2320.md
Normal file
@ -0,0 +1,40 @@
|
||||
## This $? refers to echo/printf, not a previous command. Assign to variable to avoid it being overwritten.
|
||||
|
||||
### Problematic code:
|
||||
|
||||
```sh
|
||||
mycommand
|
||||
echo "Command exited with $?"
|
||||
if [ $? -ne 0 ]
|
||||
then
|
||||
echo "Failed"
|
||||
fi
|
||||
```
|
||||
|
||||
### Correct code:
|
||||
|
||||
```sh
|
||||
mycommand
|
||||
ret=$?
|
||||
echo "Command exited with $ret"
|
||||
if [ $ret -ne 0 ]
|
||||
then
|
||||
echo "Failed"
|
||||
fi
|
||||
```
|
||||
|
||||
### Rationale:
|
||||
|
||||
ShellCheck found a `$?` that always refers to `echo` or `printf`.
|
||||
|
||||
This most commonly happens when trying to show `$?` before doing something with it, without realizing that any such action will also overwrite `$?`.
|
||||
|
||||
In the problematic example, `echo "Command exited with $?"` was intended to show the exit code before acting on it, but the act of showing `$?` also overwrote it, so the condition is always false. The solution is to assign `$?` to a variable first, so that it can be used repeatedly.
|
||||
|
||||
### Exceptions:
|
||||
|
||||
If you intentionally refer to `echo` to get the result of a write, you can ignore this message. Alternatively, write it out as in `if echo $$ > "$pidfile"; then status=0; else status=1; fi`
|
||||
|
||||
### Related resources:
|
||||
|
||||
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Loading…
x
Reference in New Issue
Block a user