Skip to content

Instantly share code, notes, and snippets.

@fumiyas
Last active December 15, 2021 03:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fumiyas/66e4989b23ce91052f32d6f206ea9d2b to your computer and use it in GitHub Desktop.
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
#!/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"
#!/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