2

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
4
  • 3
    Replace echo "$(invalid_cmd)" with invalid_cmd. Commented Oct 10, 2023 at 21:14
  • 5
    Please paste your script at shellcheck.net and try to implement the recommendations made there. Commented Oct 10, 2023 at 21:16
  • 1
    Please read mywiki.wooledge.org/BashFAQ/105 Commented Oct 10, 2023 at 22:08
  • 1
    Also see Bash Pitfalls #60 (set -euo pipefail). Commented Oct 10, 2023 at 22:09

1 Answer 1

1

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 "$?"
Sign up to request clarification or add additional context in comments.

3 Comments

I believe OP was getting the return value of the echo command, not invalid_cmd.
They were, which is why set -e didn't trigger. However, based on the context of their question, that's probably not their intention.
Ah! I'll be able to use this in the actual problem - I guess I should have provided a more detail. The example above was meant to be the most basic reproduction of my problem. Thanks for inferring the problem. The actual problem is a bit more complicated - I've been using bash as a "no dependency" template engine (probably a bad idea :)). Recently, a template change contained an error and the "template engine" didn't fail the way I'd expected which caused problems downstream. Thanks for the help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.