i currently wonder how to do error handling for chained commands. the following is just an example to easy demonstrate my problem:
cat file | gzip >/tmp/test
if cat fails (because for example file is missing), gzip is still executed and therefore the last stored exit code in $? is 0. set -e won't help either in this case.
i wonder what's the best solution for this?
thanks!
A pipe in Bash takes the standard output of one process and passes it as standard input into another process. Bash scripts support positional arguments that can be passed in at the command line.
$(...) is an expression that starts a new subshell, whose expansion is the standard output produced by the commands it runs. This is similar to another command/expression pair in bash : ((...)) is an arithmetic statement, while $((...)) is an arithmetic expression. Follow this answer to receive notifications.
|| means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).
To activate this "exit-on-error" behavior in bash, you can use the set command as follows. Once called with -e option, the set command causes the bash shell to exit immediately if any subsequent command exits with a non-zero status (caused by an error condition). The +e option turns the shell back to the default mode.
Try this:
trap 'echo "ERR caught"' ERR
set -o pipefail
cat file | gzip >/tmp/test
The output file will still be created (the creation is done in parallel) and gzip
will be run, but you can do cleanup. Use the ${PIPESTATUS[@]}
array to see where the error occurred. You can use $BASH_COMMAND
and $BASH_LINENO
for additional information regarding the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With