Last active
December 15, 2021 03:30
-
-
Save fumiyas/66e4989b23ce91052f32d6f206ea9d2b to your computer and use it in GitHub Desktop.
Shell: Get a return code (exit code) from a command on set -e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
run_and_get_rc() { | |
local _rc_vname="$1"; shift | |
local _rc | |
local _shopts="$-" | |
if [ "${_rc_vname#*[!a-z_]}" != "$_rc_vname" ]; then | |
echo "run_and_get_rc: Invaid return variable name: $_rc_vname" 1>&2 | |
exit 1 | |
fi | |
set +e | |
"$@" | |
_rc="$?" | |
eval "$_rc_vname=$_rc" | |
if [ "${_shopts#*e}" != "$_shopts" ]; then | |
set -e | |
return 0 | |
fi | |
return "$_rc" | |
} | |
set -e | |
run_and_get_rc rc ls --invalid-option-xxx | |
echo $? | |
echo "$rc" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
## | |
## https://twitter.com/eban/status/1470957323753779201 | |
set -e | |
ls --invalid-option-xxx && true | |
echo $? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment