Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unshift array element in Bash script

Tags:

arrays

bash

shell

I would like to add elements to the beginning of an array instead of to the end. Is this possible in Bash?

like image 761
Danny Avatar asked Aug 15 '16 16:08

Danny


2 Answers

If your array is contiguous, you can use the "${array[@]}" syntax to construct a new array:

array=('a' 'b' 'c');
echo "${array[@]}"; # prints: a b c
array=('d' "${array[@]}");
echo "${array[@]}"; # prints: d a b c

As chepner mentions, the above method will collapse indices of sparse arrays:

array=([5]='b' [10]='c');
declare -p array; # prints: declare -a array='([5]="b" [10]="c")'
array=('a' "${array[@]}");
declare -p array; # prints: declare -a array='([0]="a" [1]="b" [2]="c")'

(Fun fact: PHP does that too - but then again, it's PHP :P)

If you need to work with sparse arrays, you can iterate over the indices of the array manually (${!array[@]}) and increase them by one (with $((...+1))):

old=([5]='b' [10]='c');
new=('a');
for i in "${!old[@]}"; do
    new["$(($i+1))"]="${old[$i]}";
done;
declare -p new; # prints: declare -a new='([0]="a" [6]="b" [11]="c")'
like image 144
Siguza Avatar answered Oct 21 '22 02:10

Siguza


Non-bash version: POSIX shells don't really have arrays, excepting shell parameters, (i.e. $1, $2, $3, ...),but for those parameters this should work:

set - a b c ; echo $1 $3

Output:

a c

Now add "foo" to the beginning:

set - foo "$@" ; echo $1 $3

Output:

foo b
like image 44
agc Avatar answered Oct 21 '22 03:10

agc