Pattern: $?
refers to echo
/printf
Issue: -
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.
Example of incorrect code:
mycommand
echo "Command exited with $?"
if [ $? -ne 0 ]
then
echo "Failed"
fi
Example of correct code:
mycommand
ret=$?
echo "Command exited with $ret"
if [ $ret -ne 0 ]
then
echo "Failed"
fi