Shell 數組與關聯數組
1.數組
1.1. 數組定義
一對圓括號表示數組,數組元素之間用空格符號分割
xiaosi@Qunar:~$ a=(1 2 3) xiaosi@Qunar:~$ echo $a 1 xiaosi@Qunar:~$ a=("yoona" "lucy" "tom") xiaosi@Qunar:~$ echo $a yoona
1.2. 數組數
長度:用${#數組名[@或*]} 可以得到數組長度xiaosi@Qunar:~$ echo ${#a[@]} 3 xiaosi@Qunar:~$ echo ${#a[*]} 3
xiaosi@Qunar:~$ array=("yoona" "lucy" "tom") xiaosi@Qunar:~$ echo ${array[0]} yoona xiaosi@Qunar:~$ echo ${array[1]} lucy xiaosi@Qunar:~$ echo ${array[*]} yoona lucy tom xiaosi@Qunar:~$ echo ${array[@]} yoona lucy tom
xiaosi@Qunar:~$ array=("yoona" "lucy" "tom") xiaosi@Qunar:~$ echo ${array[2]} tom xiaosi@Qunar:~$ array[2]=lily xiaosi@Qunar:~$ echo ${array[2]} lily
xiaosi@Qunar:~$ array=("yoona" "lucy" "tom") xiaosi@Qunar:~$ unset array[1] xiaosi@Qunar:~$ echo ${array[*]} yoona tom xiaosi@Qunar:~$ unset array xiaosi@Qunar:~$ echo ${array[*]} xiaosi@Qunar:~$
xiaosi@Qunar:~$ array=(yoona lucy tom) xiaosi@Qunar:~$ echo ${array[*]} yoona lucy tom xiaosi@Qunar:~$ echo ${array[*]:1:2} lucy tom xiaosi@Qunar:~$ echo ${array[@]:0:1} yoona
xiaosi@Qunar:~$ array=(yoona lucy tom) xiaosi@Qunar:~$ echo ${array[@]/lucy/lily} yoona lily tom xiaosi@Qunar:~$ echo ${array[@]} yoona lucy tom
xiaosi@Qunar:~$ declare -A assArray
xiaosi@Qunar:~$ assArray=([lucy]=beijing [yoona]=shanghai) xiaosi@Qunar:~$ echo ${assArray[lucy]} beijing
xiaosi@Qunar:~$ assArray[lily]=shandong xiaosi@Qunar:~$ assArray[sunny]=xian xiaosi@Qunar:~$ echo ${assArray[sunny]} xian xiaosi@Qunar:~$ echo ${assArray[lily]} shandong
xiaosi@Qunar:~$ echo ${!assArray[*]} lily yoona sunny lucy xiaosi@Qunar:~$ echo ${!assArray[@]} lily yoona sunny lucy
元用於查找。使用${!數組名稱[@或*]}取得陣列的索引列表
#! /bin/bash declare -A cityArray cityArray=([yoona]=beijing [lucy]=shanghai [lily]=shandong) for key in ${!cityArray[*]} do echo "${key} come from ${cityArray[$key]}" done
2.3 取得所有鍵值對
xiaosi@Qunar:~/company/sh$ bash array.sh lily come from shandong yoona come from beijing lucy come from shanghai
結果:rrreee
,謝謝大家對本站的支持! 更多Shell 數組與關聯數組詳解及實例代碼相關文章請關注PHP中文網!