Script wrapper to exit the main script with debugging

I have a bash script that executes several commands in order and stops if one returns a non-zero error code and displays a line number to help find the command.

After each command, I run a function (exitIfLastCommandReturnCodeNotZero), which checks if the exit code was in order, and if it does not display the line number and error code. For instance:

.. 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 script that can simply wrap commands and give me the same functionality? For instance:

 .. wrapperScript cmd1 param1 param2 wrapperScript cmd2 param1 param2 wrapperScript cmd3 param1 param2 .. 

or even better, a block-level function that runs all commands and exits if one command fails. For instance:

 WRAPPERSCRIPT_PSEUDOCODE { .. cmd1 param1 param2 cmd2 param1 param2 cmd3 param1 param2 .. } 

Ideally, the output when a command fails should also include (in addition to the line number) the name and parameters of the command.

+4
source share
2 answers

Use a trap. You can turn the trap on and off in different places of your code if you want.

 #!/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?

+2
source

I suggest starting each script with set -Eeu .

See related entry: Error Handling in Bash

0
source

Source: https://habr.com/ru/post/1341001/


All Articles