Bash command status check

Bash command status check

  • Do not check for command output - it might fail to detect failure
  • Check for command return value instead
run_ls() {
    ls "$@" || { echo 'RUN_FAILED'; }
}
# missing \ at the end of line below
CMD_OUTPUT=$(run_ls
               -a
)

if [[ "$CMD_OUTPUT" == *"RUN_FAILED"* ]]; then
    echo 'Fail'
else
    echo 'Pass'
fi


~ ❯ ./test.sh  
./test.sh: line 8: -a: command not found
Pass
run_ls() {
    ls "$@" || { return 1; }
}
# missing \ at the end of line below
CMD_OUTPUT=$(run_ls
    -a
)
CMD_STATUS=$?
if [[ $CMD_STATUS -ne 0 ]]; then
    echo 'Fail'
else
    echo 'Pass'
fi


~ ❯ ./test2.sh  
./test2.sh: line 8: -a: command not found
Fail

Last modified on 2025-06-21