I have a function
function f() {
command 1
command 2
command 3
command 4
}
I want function f() to somehow tell me there is an error if any of the 4 commands fails.
I also don't want to set -e. I want four commands all run, even if one fails.
How do I do that? Sorry for the newbie question -- I am quite new to bash scripting.
If I understand what you're asking correctly, you can do this:
f() {
err=""
command 1 || err=${err}1
command 2 || err=${err}2
command 3 || err=${err}3
command 4 || err=${err}4
# do something with $err to report the error
}
Of course, instead of using a variable you could simply put echo commands after the || if all you need to do is print an error message:
f() {
command 1 || echo "command 1 failed" >&2
command 2 || echo "command 2 failed" >&2
command 3 || echo "command 3 failed" >&2
command 4 || echo "command 4 failed" >&2
}
Take advantage of "$@" and write a higher-order function:
function warner () { "$@" || echo "Error when executing '$@'" >&2; }
Then:
warner command 1
warner command 2
warner command 3
warner command 4
Test:
$ warner git status
fatal: Not a git repository (or any of the parent directories): .git
Error when executing 'git status'
$ warner true
As @user1261959 found out, this is the same approach as in this answer.
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