Reputation: 1336
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.
Upvotes: 2
Views: 933
Reputation: 212228
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"
Upvotes: 1
Reputation: 14432
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)
Upvotes: 0
Reputation: 872
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.
Upvotes: 0