Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash function return status

Tags:

linux

bash

shell

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.

like image 836
CuriousMind Avatar asked Dec 01 '25 15:12

CuriousMind


2 Answers

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
}
like image 125
Random832 Avatar answered Dec 04 '25 07:12

Random832


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.

like image 23
coredump Avatar answered Dec 04 '25 08:12

coredump



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!