Shell 數組與關聯陣列詳解及執行個體代碼

來源:互聯網
上載者:User
Shell 數組與關聯陣列

1.數組

1.1. 數組定義

一對圓括弧表示數組,數組元素之間用空格符號分割

xiaosi@Qunar:~$ a=(1 2 3)xiaosi@Qunar:~$ echo $a1xiaosi@Qunar:~$ a=("yoona" "lucy" "tom")xiaosi@Qunar:~$ echo $ayoona

1.2. 數組長度,元素,賦值與刪除

長度:用${#數組名[@或*]} 可以得到數組長度

xiaosi@Qunar:~$ echo ${#a[@]}3xiaosi@Qunar:~$ echo ${#a[*]}3

擷取元素:用${數組名[下標]} 得到數組元素(下標從0開始), 下標為*或者@得到整個數組內容

xiaosi@Qunar:~$ array=("yoona" "lucy" "tom")xiaosi@Qunar:~$ echo ${array[0]}yoonaxiaosi@Qunar:~$ echo ${array[1]}lucyxiaosi@Qunar:~$ echo ${array[*]}yoona lucy tomxiaosi@Qunar:~$ echo ${array[@]}yoona lucy tom

賦值:通過數組名[下標]可以對其進行引用賦值,如果下標不存在,自動添加新一個數組元素

xiaosi@Qunar:~$ array=("yoona" "lucy" "tom")xiaosi@Qunar:~$ echo ${array[2]}tomxiaosi@Qunar:~$ array[2]=lilyxiaosi@Qunar:~$ echo ${array[2]}lily

刪除:通過unset數組[下標]可以清除相應的元素,不帶下標則清除全部資料

xiaosi@Qunar:~$ array=("yoona" "lucy" "tom")xiaosi@Qunar:~$ unset array[1]xiaosi@Qunar:~$ echo ${array[*]}yoona tomxiaosi@Qunar:~$ unset arrayxiaosi@Qunar:~$ echo ${array[*]}xiaosi@Qunar:~$

1.3. 擷取某範圍的元素

直接通過 ${數組名[@或*]:起始位置:長度} 擷取數組給定範圍內元素,返回字串,中間用空格分開

xiaosi@Qunar:~$ array=(yoona lucy tom)xiaosi@Qunar:~$ echo ${array[*]}yoona lucy tomxiaosi@Qunar:~$ echo ${array[*]:1:2}lucy tomxiaosi@Qunar:~$ echo ${array[@]:0:1}yoona

1.4. 替換

${數組名[@或*]/尋找字元/替換字元} 該操作不會改變原先數組內容,如果需要修改,可以看上面例子

xiaosi@Qunar:~$ array=(yoona lucy tom)xiaosi@Qunar:~$ echo ${array[@]/lucy/lily}yoona lily tomxiaosi@Qunar:~$ echo ${array[@]}yoona lucy tom

2. 關聯陣列

Bash支援關聯陣列,它可以使用字串作為數組索引,有時候採用字串索引更容易理解。

2.1 定義關聯陣列

首先需要使用聲明語句將一個變數聲明為關聯陣列。

xiaosi@Qunar:~$ declare -A assArray

聲明之後,可以有兩種方法將元素添加到關聯陣列中。

(1)利用內嵌索引-值列表的方法

xiaosi@Qunar:~$ assArray=([lucy]=beijing [yoona]=shanghai)xiaosi@Qunar:~$ echo ${assArray[lucy]}beijing

(2)使用獨立的索引-值進行賦值

xiaosi@Qunar:~$ assArray[lily]=shandongxiaosi@Qunar:~$ assArray[sunny]=xianxiaosi@Qunar:~$ echo ${assArray[sunny]}xianxiaosi@Qunar:~$ echo ${assArray[lily]}shandong

2.2 列出數組索引

每一個數組都有一個索引用於尋找。使用${!數組名[@或者*]}擷取數組的索引列表

xiaosi@Qunar:~$ echo ${!assArray[*]}lily yoona sunny lucyxiaosi@Qunar:~$ echo ${!assArray[@]}lily yoona sunny lucy

2.3 擷取所有索引值對

#! /bin/bashdeclare -A cityArraycityArray=([yoona]=beijing [lucy]=shanghai [lily]=shandong)for key in ${!cityArray[*]}do echo "${key} come from ${cityArray[$key]}"done

結果:

xiaosi@Qunar:~/company/sh$ bash array.shlily come from shandongyoona come from beijinglucy come from shanghai

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.