Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash get exit status of command when 'set -e' is active?

Tags:

bash

I generally have -e set in my Bash scripts, but occasionally I would like to run a command and get the return value.

Without doing the set +e; some-command; res=$?; set -e dance, how can I do that?

like image 732
David Wolever Avatar asked Sep 04 '13 19:09

David Wolever


2 Answers

as an alternative

ans=0 some-command || ans=$? 
like image 30
KitsuneYMG Avatar answered Sep 28 '22 00:09

KitsuneYMG


From the bash manual:

The shell does not exit if the command that fails is [...] part of any command executed in a && or || list [...].

So, just do:

#!/bin/bash  set -eu  foo() {   # exit code will be 0, 1, or 2   return $(( RANDOM % 3 )) }  ret=0 foo || ret=$? echo "foo() exited with: $ret" 

Example runs:

$ ./foo.sh foo() exited with: 1 $ ./foo.sh foo() exited with: 0 $ ./foo.sh foo() exited with: 2 

This is the canonical way of doing it.

like image 128
Adrian Frühwirth Avatar answered Sep 28 '22 01:09

Adrian Frühwirth