Interview Prep/Shell Scripting/Arrays, conditionals and loops

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops