Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error handling with chained commands (pipes) in a bash script?

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!

like image 983
aurora Avatar asked Dec 17 '10 16:12

aurora


People also ask

Can you pipe in a bash script?

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.

What are $( and $(( )) in bash?

$(...) 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.

What does || mean in shell?

|| means execute the statement which follows only if the preceding statement failed (returned a non-zero exit code).

How do you handle errors in bash script?

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.


1 Answers

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.

like image 143
Dennis Williamson Avatar answered Sep 28 '22 06:09

Dennis Williamson