Skip to content

Instantly share code, notes, and snippets.

@emanuele6
Created May 31, 2022 00:29
Show Gist options
  • Save emanuele6/1d41604a8c233a95227c78d7f2b0a3b8 to your computer and use it in GitHub Desktop.
Save emanuele6/1d41604a8c233a95227c78d7f2b0a3b8 to your computer and use it in GitHub Desktop.
BASH_REMATCH stack: a secret bash feature :O
#!/bin/bash --
# https://lists.gnu.org/archive/html/bug-bash/2022-05/msg00052.html
bashrematch_push () {
local BASH_REMATCH a
for a
do [[ $a =~ .* ]]
done
}
bashrematch_pop () {
local i
for (( i = (${1-1}); i; --i )); do
printf '%s\n' "$BASH_REMATCH"
unset -v BASH_REMATCH
done
}
# Examples:
# bash-5.1$ printf '%s\n' a b c | bashrematch_tac
# c
# b
# a
#
# bash-5.1$ printf 'd\ne\nf\ng' | bashrematch_tac
# gf
# e
# d
bashrematch_tac () {
local REPLY i=0
while read -r; do
bashrematch_push "$REPLY"
(( ++i ))
done
printf '%s' "$REPLY"
bashrematch_pop "$i"
}
# Examples:
# bash-5.1$ a=( el1 el2 el3 ); bashrematch_reverse "${a[@]}"
# el3
# el2
# el1
bashrematch_reverse () {
bashrematch_push "$@"
bashrematch_pop "$#"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment