Search code examples
bashexit-codecommand-substitution

Fail bash script when command expansion fails


I'd like to be able to warn and fail if the following command expansion fails:

#!/usr/bin/env bash
set -Eeuo pipefail

echo "$(invalid_cmd)"
echo "$?"

Instead of failing, I get the following output:

./script.sh: line 5: invalid_cmd: command not found

0

Solution

  • Use a temporary variable. The exit status of variable assignment is the exit status of last command executed - in this case $(...).

    tmp="$(invalid_cmd)"
    ret="$?"  # won't get here, set -e will trigger
    echo "$tmp"
    echo "$ret"
    

    Overall, echo "$(stuff)" is just stuff. Just run the command, no need to get the to command output to print it, command already prints it.

    invalid_cmd
    echo "$?"