How can I run a function as a "tested command" and perform action on failure, while still aborting the function as soon as an error occur? Consider the following script
#!/bin/bash -e
function foo() {
echo Entering foo
false
echo Should not reach this line
}
foo || echo I want to see this line on failure in foo
foo
The output I'm getting is
Entering foo
Should not reach this line
Entering foo
While I would like to get
Entering foo
I want to see this line on failure in foo
Entering foo
I guess what I'm looking for is a way to mark the function as untested command. According bash man page
-e errexit
Exit immediately if any untested command fails in non-interactive
mode. The exit status of a command is considered to be explicitly
tested if the command is part of the list used to control an if,
elif, while, or until; if the command is the left hand operand of
an “&&” or “||” operator; or if the command is a pipeline preceded
by the ! operator. If a shell function is executed and its exit
status is explicitly tested, all commands of the function are con‐
sidered to be tested as well.
EDIT The expected output was wrong. edited it for clarity
set -e
is disabled in the first call of foo
since it's on the left hand side of ||
.
Also, you would never see the I want to see this ...
string being outputted, unless the last echo
in foo
somehow failed (it's that last echo
in foo
that determines the exit status of the function).
foo() {
echo Entering foo
false && echo Should not reach this line
}
foo || echo I want to see this line on failure in foo
foo
The above outputs (with or without set -x
)
Entering foo
I want to see this line on failure in foo
Entering foo
Now false
is the last executed statement in foo
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With