我想將數組添加到數組的開頭而不是結尾。這在Bash中可能嗎?在Bash腳本中unshift數組元素
回答
如果陣列是連續的,則可以使用"${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")'
是的,這是可能的,見下面的例子:
#!/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")'
您可能會發現'declare -p MyArray'是可視化數組內容的有用方法。 – ghoti
@ ghoti謝謝,我不知道這件事。 – AtomHeartFather
......或者至少'printf'%q \ n'「$ {MyArray [@]}」' - 用'echo「$ {MyArray [@]}」',你無法區分' MyArray =(hello world)'和'MyArray =(「hello world」)' –
非慶典版本:POSIX炮彈真的沒有陣列,除了外殼參數(即$ 1,$ 2,$ 3 ...),但這些參數可以這樣:
set - a b c ; echo $1 $3
輸出:
a c
現在加入「富」來開頭:
set - foo "[email protected]" ; echo $1 $3
輸出:
foo b
- 1. 加載數組元素的腳本
- 2. bash腳本中的參數分組
- 3. bash - 在bash腳本中使用getopts和關聯數組
- 4. 在Java腳本中計算數組元素的平均值?
- 5. 如何在shell腳本中處理Perl數組元素?
- 6. 數組可以在unix腳本中存儲多少個元素?
- 7. 在shell腳本中將元素存儲回數組
- 8. 如何在shell腳本中選擇數組元素?
- 9. 使用包含命令空格的元素生成bash腳本數組
- 10. bash腳本刪除pdf元數據
- 11. 計數器在bash腳本
- 12. 在bash腳本
- 13. $ *在bash腳本
- 14. 在bash腳本
- 15. 在bash腳本
- 16. 在bash腳本
- 17. 在bash腳本
- 18. jq - csv與數組json的bash腳本?
- 19. Bash腳本 - 如何填充數組?
- 20. 分配值數組(bash腳本錯誤)
- 21. bash腳本變量數組名
- 22. 在Linux bash腳本中的Perl腳本
- 23. bash腳本參數
- 24. 在Bash腳本中比較數組中的字符串
- 25. java腳本中數組末尾的未知元素?
- 26. shell腳本中的數組的最大元素及其索引
- 27. 尋找在bash數組中的元素和打印排出來
- 28. 對多維數組使用unshift函數
- 29. 「或」在bash腳本中
- 30. 在Bash中刪除腳本
你能砍在數組的開頭或結尾的快速陣列重新分配,但沒有什麼在bash是會插入一個索引。爲什麼不嘗試編寫函數來重寫數組,如果遇到問題,請在StackOverflow上尋求幫助?我們大多數人都很樂意幫助您修復代碼,但通常不願意擔任無償的短訂單編程人員。 – ghoti