Running
$ echo $BASH_VERSION
4.3.42(1)-release
given these two functions:
ashift ()
{
declare -n arr;arr="$1"
((${#arr[@]} == 0)) && return
echo "${arr[0]"}
arr=("${arr[@]:1}")
}
apop ()
{
declare -n arr="$1";shift
((${#arr[@]} == 0)) && return
echo "${arr[-1]}"
arr=("${arr[@]:0:$((${#arr[@]}-1))}")
}
the 'natural' way to use them would be
declare -a thearray
thearray=(a b c d e f g)
p=$(apop thearray)
s=$(ashift thearray)
echo "p=$p, thearray=${thearray[@]}, s=$s"
However, the output is not what you would expect:
p=g, thearray=a b c d e f g, s=a
That is because (I think) we are running the ashift
and apop
in a subshell to capture the output. If I do not capture the output:
declare -a thearray
thearray=(a b c d e f g)
apop thearray
ashift thearray
echo "thearray=${thearray[@]}"
the output (intermixed with the commands) is
g
a
thearray=b c d e f
So, does anyone know how I can run the apop
and ashift
commands in the current process AND capture the output?
Note: For completeness, these work because there is no capturing, so you don't ever run them in a subshell:
aunshift ()
{
declare -n arr;arr="$1";shift
arr=("$@" "${arr[@]}")
}
apush ()
{
declare -n arr;arr="$1";shift
arr+=("$@")
}