3

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.

CuriousMind
  • 15,168
  • 20
  • 82
  • 120
  • this link also helpful : [http://stackoverflow.com/questions/32990525/check-all-commands-exit-code-within-a-bash-script/32990797#32990797](http://stackoverflow.com/questions/32990525/check-all-commands-exit-code-within-a-bash-script/32990797#32990797) – Nullpointer Oct 26 '15 at 10:30
  • @user1261959 This is basically what I am doing in my answer. I did not found an existing answer, otherwise I would have linked to it. Thanks. – coredump Oct 26 '15 at 11:52

3 Answers3

4

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
}
Random832
  • 37,415
  • 3
  • 44
  • 63
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.

Community
  • 1
  • 1
coredump
  • 37,664
  • 5
  • 43
  • 77
  • Well the problem is command 1 - command n still need to be run regardless whether something fails in the middle. It's just nice to know that something fails. – CuriousMind Oct 26 '15 at 03:41
  • @CodeNoob Sorry for the misunderstanding, totally rewrote the answer. – coredump Oct 26 '15 at 03:48
0

You can check the exit flag of any of your commands after they run by checking the variable $?.If it returns 0 usually everything went well otherwise it means an error occurred. You can make your function return a flag to the caller by using the keyword return

Tom
  • 54
  • 4