On Sat, Oct 15, 2016 at 11:12 AM, Marco Ippolito <maroloc...@gmail.com> wrote: > Bash has elegant and powerful constructs like `mapfile', > yet it is missing something as easy as an array "pop". > > Extract the last value of an array at the same time as > removing it from the array. > > Is this the best one can do? > > $ a=(1 2 3); v=${a[-1]}; unset 'a[-1]'; printf '%s\n' "$v" "${a[@]}" > > The 2-step approach gets tiresome after a while. > > For positional parameters, it _does_ have `shift'... > ... maybe it could add a `pop`, somehow? >
Since you're using Bash-4.3 (or 4.4), you can create a function that uses declare -n: $ function array_pop { declare -n __a=$1; __=${__a[-1]}; unset '__a[-1]'; } $ a=(1 2 3); array_pop a; printf '%s\n' "$__" "${a[@]}" 3 1 2 And my simple rule to using functions that process variables with -n: don't pass variables that begin with two underscores. There's another way to avoid variable name conflicts, and that is to prefix the reference variables with the name of the function itself, but I find that already an overkill. You can also improve the function by adding sanity checks, but that's the basic concept of it. -- konsolebox