2016-08-15 86 views
1

我想將數組添加到數組的開頭而不是結尾。這在Bash中可能嗎?在Bash腳本中unshift數組元素

+0

你能砍在數組的開頭或結尾的快速陣列重新分配,但沒有什麼在bash是會插入一個索引。爲什麼不嘗試編寫函數來重寫數組,如果遇到問題,請在StackOverflow上尋求幫助?我們大多數人都很樂意幫助您修復代碼,但通常不願意擔任無償的短訂單編程人員。 – ghoti

回答

5

如果陣列是連續的,則可以使用"${array[@]}"語法來構造新的數組:

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

作爲chepner mentions,上述方法將崩潰稀疏數組的索引:

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")' 

(有趣的事實:PHP does that too - 但是再次,it's PHP:P)

如果您需要使用稀疏數組,您可以Ñ遍歷陣列手動(${!array[@]})的索引,並通過一個增加它們(用$((...+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")' 
+1

你打敗了我!另外,你有正確的引號:-) – AtomHeartFather

+0

非常感謝你!在Google上搜索但找不到任何內容! –

+0

這隻適用於連續陣列。 – chepner

3

是的,這是可能的,見下面的例子:

#!/bin/bash 
MyArray=(Elem1 Elem2); 
echo "${MyArray[@]}" 
MyArray=(Elem0 "${MyArray[@]}") 
echo "${MyArray[@]}" 

作爲每@ ghoti的評論,declare -p MyArray可以用來很好地顯示數組的內容。當在上面的腳本結束調用,它輸出:

declare -a MyArray='([0]="Elem0" [1]="Elem1" [2]="Elem2")' 
+0

您可能會發現'declare -p MyArray'是可視化數組內容的有用方法。 – ghoti

+0

@ ghoti謝謝,我不知道這件事。 – AtomHeartFather

+0

......或者至少'printf'%q \ n'「$ {MyArray [@]}」' - 用'echo「$ {MyArray [@]}」',你無法區分' MyArray =(hello world)'和'MyArray =(「hello world」)' –

1

慶典版本:POSIX炮彈真的沒有陣列,除了外殼參數(即$ 1,$ 2,$ 3 ...),但這些參數可以這樣:

set - a b c ; echo $1 $3 

輸出:

a c 

現在加入「」來開頭:

set - foo "[email protected]" ; echo $1 $3 

輸出:

foo b