Fail bash script when command expansion fails

67 Views Asked by At

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
1

There are 1 best solutions below

3
KamilCuk On BEST ANSWER

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 "$?"