I want to display a error log line for one particular command when its return value is nonzero . I am using ' set -e ' for terminating if any command returns nonzero value along with ' trap ' for this
#!/bin/bash
set -e
log_report() {
echo "Error on line $1"
}
trap 'log_report $LINENO' ERR
echo "starting ..."
first_badcommand
echo "running"
second_badcommd
OUTPUT:
starting ...
/tmp/test1.sh: line 10: first_badcommand: command not found
Error on line 10
since i use set -e the script exit and showing my error log for first_badcommand.. itself. I want to exit with error log for only a particular command giving non zero return code and for rest of commands giving non zero return code, exit without error log
After clarification, it appears that the requirement is to exit the script if any error happens, but that the commands which are described as "badcommand" in the question, might or might not fail.
In this answer, I am naming the commands simply first_command
etc, to reflect the fact they might or might not fail.
The set -e
command, as suggested in the question, will indeed terminate the script if an error occurs, and the trap ... ERR
installs a handler which will run after an error (and before the script exits where set -e
has been used).
In this case, you should:
wait until the trap is required before installing it (it does not need to be done at/near the start of the script)
disable the trap again when it is no longer required, using trap - ERR
so that commands to enable and disable the trap surround the command for which the trap is required.
For example:
#!/bin/bash
set -e
log_report() {
echo "Error on line $1"
}
echo "starting ..."
first_command
trap 'log_report $LINENO' ERR
echo "running"
second_command
trap - ERR
echo "still running"
third_command
This will exit if any command fails (because of the set -e
at the top), but the trap will only be run if second_command
fails.
(Note also that set -e
similarly does not need to be applied at the start of the script. It can be enabled at any point, and disabled again using set +e
. But in this example, it appears that the exit-on-error behaviour is required throughout.)