-
-
Save cbugk/4424ac68477c5dd509ac6c5bd39a7fa0 to your computer and use it in GitHub Desktop.
bash defer function - just like go's defer()
This file contains hidden or 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
function _run_deferred() { | |
local _depth="$BASHPID.${#FUNCNAME[@]}" | |
[[ "$_depth" != "$_deferred_depth" ]] && return | |
local opt=$- | |
set +e | |
for (( i=${#_deferred[@]} - 1; i >= 0; i-- )); do | |
eval "${_deferred[i]}" | |
done | |
[[ "$opt" == *e* ]] && set -e | |
} | |
function _defer() { | |
_deferred_depth="$BASHPID.${#FUNCNAME[@]}" | |
_deferred+=( "$(printf '%q ' "$@")" ) | |
} | |
# This has to be an alias so that the `trap ... RETURN` runs appropriately. | |
shopt -s expand_aliases | |
alias defer='declare -a _deferred; declare _deferred_depth; trap _run_deferred EXIT RETURN; _defer' |
This file contains hidden or 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
function foo1() { echo foo1; } | |
function foo2() { defer echo foo2; foo1; } | |
function foo3() { foo2; } | |
function foo4() { echo foo4-begin; ( defer echo foo4-subshell; foo3; ); echo foo4-end; } | |
foo4 |
This file contains hidden or 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
foo4-begin | |
foo1 | |
foo2 | |
foo4-subshell | |
foo4-end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment