Last active
September 18, 2024 07:58
-
-
Save phemmer/e943dce38eaa948f1893d9392741970f to your computer and use it in GitHub Desktop.
bash defer function - just like go's defer()
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
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 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 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
Short snippets like this are almost never considered substantial enough to be licenceable. The reason being that someone could reasonably come up with an identical solution fairly quickly.