2

In the following scenario

$ echo $(cat some-file-that-doesnt-exist)

I'd like to have the outer command fail (exit code != 0) if the inner command fails.

3 Answers 3

1

The cleanest way (and at the moment the only way I can think of, although it wouldn't surprise me if bash has some option setting that short-circuits the standard process and does what you want, but I would be loathe to use such a thing if it does exist) is to break up the command into pieces. That is:

$ content=$(cat /p/a/t/h) && echo "$content"
Sign up to request clarification or add additional context in comments.

Comments

0

If you only need stopping the command chain on error (instead of propagating their exit code) you can use logical AND operator &&:

x=$(cat some-file-that-doesnt-exist) && echo "$x"

Combine with logical or || you can do:

x=$(cat input.a) || x=$(cat input.b) || x=$(cat input.c) && echo "input is: $x"

Where echo only run when one or more file exists.

Comments

0

For the case of cat as the inside command, you can use the $(<filename structure. This will effectively eliminate the internal command, and will cause error processing (set -e, ERR trap, ...) to get triggered if the file does not exists

x=$(</path/to/file)

1 Comment

echo $(<missing-file) ; echo $? yields 0. I need it to yield anything different than 0. If I need to have the extraction into variable, then essentially this is the same answer as the others.

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.