## 一對括號表示數組,數組元素用"空格"符號分隔開 1. 直接賦值 a=(1 2 3 4) 2. seq a=$(seq 1 11) # 表示生成一個從1到11的數組,步進爲1. b=$(seq 1 3 11) # 表示生成一個 1,4,7,10 的數組,步進爲3. 3. .. 擴展 a=$(echo {1..4})
1. 直接echo輸出: [yongfu@yf-20: ~] 15:54:12 $ a=(1 2 3 4) [yongfu@yf-20: ~] 15:54:18 $ echo ${a[@]} # 輸出整個數組 1 2 3 4 [yongfu@yf-20: ~] 15:54:20 $ echo ${a[*]} # 輸出整個數組 1 2 3 4 [yongfu@yf-20: ~] 15:54:26 $ echo $a # $a並不表示數組,只表示數組的第一個元素${a[0]} 1 [yongfu@yf-20: ~] 15:54:33 $ echo ${a[3]} # 輸出第"四"個元素 4 2. for 循環輸出 [yongfu@yf-20: ~] 15:41:36 $ a=(1 2 3 4) [yongfu@yf-20: ~] 15:50:04 $ for i in ${a[@]} ; do echo $i ; done 1 2 3 4
[yongfu@yf-20: ~] 15:54:39 $ echo ${!a[@]} 0 1 2 3
[yongfu@yf-20: ~] 15:56:31 $ echo ${#a[@]} 4
[yongfu@yf-20: ~] 15:58:05 $ a[1]=100 [yongfu@yf-20: ~] 15:59:09 $ echo ${a[@]} 1 100 3 4
直接經過 數組名[下標] 就能夠對其進行引用賦值,若是下標不存在,自動添加新一個數組元素數組
[yongfu@yf-20: ~] 16:01:25 $ a[4]=200 [yongfu@yf-20: ~] 16:01:43 $ echo ${a[@]} 1 100 3 4 200
直接經過:unset 數組[下標] 能夠清除相應的元素,不帶下標,清除整個數據。code
[yongfu@yf-20: ~] 16:01:47 $ a=(1 2 3 4 5) [yongfu@yf-20: ~] 16:04:07 $ unset a [yongfu@yf-20: ~] 16:04:12 $ echo ${a[@]} [yongfu@yf-20: ~] 16:04:20 $ a=(1 2 3 4 5) [yongfu@yf-20: ~] 16:04:35 $ unset a[1] [yongfu@yf-20: ~] 16:04:43 $ echo ${a[@]} 1 3 4 5 [yongfu@yf-20: ~] 16:04:47 $ echo ${#a[@]} 4
直接經過 ${數組名[@或*]:起始位置:長度} 切片原先數組,返回是字符串,中間用「空格」分開,所以若是加上」()」,將獲得切片數組,上面例子:c 就是一個新數據。字符串
[yongfu@yf-20: ~] 16:04:56 $ a=(1 2 3 4 5) [yongfu@yf-20: ~] 17:09:40 $ echo ${a[@]:0:3} 1 2 3 [yongfu@yf-20: ~] 17:09:50 $ echo ${a[@]:1:4} 2 3 4 5 [yongfu@yf-20: ~] 17:09:55 $ c=(${a[@]:1:4}) [yongfu@yf-20: ~] 17:10:05 $ echo ${#c[@]} 4 [yongfu@yf-20: ~] 17:10:13 $ echo ${c[@]} 2 3 4 5
調用方法是:${數組名[@或*]/查找字符/替換字符} 該操做不會改變原先數組內容,若是須要修改,能夠看上面例子,從新定義數據。擴展
[yongfu@yf-20: ~] 17:11:17 $ a=(1 2 3 4 5) [yongfu@yf-20: ~] 17:11:19 $ echo ${a[@]/3/100} 1 2 100 4 5 [yongfu@yf-20: ~] 17:11:25 $ echo ${a[@]} 1 2 3 4 5 [yongfu@yf-20: ~] 17:11:32 $ a=(${a[@]/3/100}) [yongfu@yf-20: ~] 17:11:38 $ echo ${a[@]} 1 2 100 4 5