Home > Back-end >  When this function will be triggered because trap commnad?
When this function will be triggered because trap commnad?

Time:09-18

Given the following code:

set -e
my_func() {
    echo "Error.. some msg"
    exit
}
trap 'my_func ${LINENO}' ERR  
  1. What are the arguments that this function (my_func) gets while have error (apart of the argument $LINENO as the first argument, but what are the other arguments?
  2. When this function will be triggered ? (in which cases of errors?)

CodePudding user response:

What are the arguments that this function (my_func) gets while have error (apart of the argument $LINENO as the first argument, but what are the other arguments?

That is... easy to check. The following code outputs 1:

$ ( set -e; f() { echo $#; }; trap 'f $LINENO' ERR; false )
1

There is only one argument.

When this function will be triggered ?

Mostly when a command exits with non-zero exit status. Before using set -e required reading: https://mywiki.wooledge.org/BashFAQ/105 .

in which cases of errors?

Depends on the particular command. For example, false command exits with non-zero exit status, it's not an "error" for that command to do that. For example grep exits with 1 if no lines were selected, and with 2 if an error occured.


"If a sigspec is ERR, the command arg is executed whenever a pipeline, a list, or a compound command returns a non-zero exit status". I looking for examples that will explain these words better.

cat file | grep '['

This pipeline will exit with 2 exit status, because [ is invalid regular expression, which will make grep fail. The exit status of pipeline is the exit status of the last command, so it is grep, so it exits with 2, and triggers ERR trap.

(Additionally, because there is no file named file on my working directory, cat will also fail, if pipefail option is enabled the pipeline will fail with the non-zero exit status of cat. That will also trigger ERR)

[[ -e file ]] && [[ -r file ]]

Because there is no file file on my working directory, this list will fail at the first [[ command, and the list will exit with the non-zero exit status returned by first [[ command. And will trigger ERR trap.

if [[ -e /dev ]]; then grep '['; fi

The exit status of if compound command is zero if no body was executed, otherwise is the exit status of the last command in the body. Because grep '[' will fail, the exit status of if will be non-zero, and that will also trigger ERR.

  • Related