I have a bash script that runs several commands in order and stops i开发者_如何学JAVAf one returns a non zero error code and displays the line number to help locate the command.
After each command I run a function (exitIfLastCommandReturnCodeNotZero) that checks if the exit code was ok and if not it displays the line number and error code. For example:
..
cmd1 param1 param2 ; exitIfLastCommandReturnCodeNotZero $? $LINENO
cmd2 param1 param2 ; exitIfLastCommandReturnCodeNotZero $? $LINENO
cmd3 param1 param2 ; exitIfLastCommandReturnCodeNotZero $? $LINENO
..
This works well but is there a built-in function or a script which can just wrap the commands and give me the same functionality? For example:
..
wrapperScript cmd1 param1 param2
wrapperScript cmd2 param1 param2
wrapperScript cmd3 param1 param2
..
or even better a 'block' level function which runs all commands and exits if one command fails. For example:
WRAPPERSCRIPT_PSEUDOCODE {
..
cmd1 param1 param2
cmd2 param1 param2
cmd3 param1 param2
..
}
Ideally, the output when a command fails should also include (apart from the line number) the command name and parameters.
Use a trap. You can turn the trap on and off at various places in your code if you like.
#!/bin/bash
function error
{
local err=$?
echo "error# $err on line $BASH_LINENO: $BASH_COMMAND"
exit $err
}
trap error ERR
# Some commands ...
echo bar
/bin/false foo # For testing
echo baz
exitIfLastCommandReturnCodeNotZero
seriously?
I would suggest starting each script with set -Eeu
.
See related post: Error handling in Bash
精彩评论