CuriousMind
CuriousMind

Reputation: 15808

bash function return status

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.

Upvotes: 3

Views: 373

Answers (3)

coredump
coredump

Reputation: 38967

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.

Upvotes: 2

Random832
Random832

Reputation: 39090

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
}

Upvotes: 4

Tom
Tom

Reputation: 54

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

Upvotes: 0

Related Questions