Why is `if cmd; then` better than running `cmd` and checking `$?` afterwards?
BeginnerConceptArrays, conditionals and loops
Answer
if tests a command's exit status directly, so you rarely need $?:
# Weak: $? is overwritten by any command in between, and set -e may exit first
grep -q ERROR app.log
if [ $? -eq 0 ]; then alert; fi
# Strong
if grep -q ERROR app.log; then alert; fi
Use $? only when you must branch on specific codes: rc=0; cmd || rc=$?; case $rc in 1) ... ;; 2) ... ;; esac. ShellCheck reports the weak form as SC2181.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate