Why testing "$?" to see if the command was successful or not, anti-pattern?

I see here that testing is $? is zero (success) or something else (failure) is an anti-pattern, but I could not find it anywhere else.

Adhering to the definition of anti-pattern on Wikipedia : β€œAn anti-pattern (or anti-pattern) is a common response to a recurring problem that is usually ineffective and runs the risk of being extremely counterproductive.” Why would this be an anti-pattern?

+6
source share
1 answer

, , , .

if your_command; then ...

,

your_command
if [ "$?" -eq 0 ]; then ...

, : echo , $? , , , your_command .

:

your_command
echo "Finished running your_command" >&2
if [ "$?" -eq 0 ]; then ...

... , .


, , , , , :

# whitelisting a nonzero value for an example of when "if your_command" won't do.
your_command; your_command_retval=$?
echo "Finished running your_command" >&2 ## now, adding more logging won't break the logic.
case $your_command_retval in
  0|2) echo "your_command exited in an acceptable way" >&2;;
  *)   echo "your_command exited in an unacceptable way" >&2;;
esac

: your_command if, , set -e ERR.

:

set -e
your_command
if [ "$?" -eq 0 ]; then ...

... ( , set -e) if $? 0, set -e . :

set -e
if your_command; then ...

... your_command set -e.

+11

All Articles