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?
as an alternative
ans=0 some-command || ans=$?
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.
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