bash提供一維數組,在數組元素的最大數目上並無約束,甚至,不要求數組元素被連續賦值,其下標從0開始。
創建與賦值
一個數組可以通過如下方式複製而自動創建
name[subscript]=value
其中下標subscript必須爲整數,大於或等於0。
也可以顯式的聲明如下:
declare -a name
# 或者
declare -a name[subscript]
# shell解釋時會忽略subscript
用如下方式可對整個數組賦值
name=(var1 var2 … varn)
也可以在賦值創建時候就指定對哪個元素賦值
name=([0]=1 [2]=34 [3]=45)
這樣,在賦值的時候跳過對下標1的賦值,則變爲空
$ echo ${name[0]}
1
$ echo ${name[1]}
$ echo ${name[2]}
34
數組元素可以是字符串,元素間以環境變量IFS分隔
$ name=(hello glad to see you)
$ echo ${name[0]}
hello
若要跨過分隔約束,可以用引號括起,單引號雙引號都可以
$ name=(hello “glad to” see you)
$ echo ${name[1]}
glad to
數組引用
在引用數組變量時,用 ${name[subscript]}
,必須要加上{ }
,否則shell無法解釋。
若下標爲@
或*
,則作爲通配符解釋,代指所有的數組元素,但不可對這個兩個作爲下標賦值。
$ echo ${name[@]}
1 34 45
$ echo ${name[*]}
1 34 45
$ name[*]=23
-bash: name[*]: bad array subscript
數組元素個數以${#name[@]}
或者${#name[*]}
獲得。
$ name=(1 2 3 4)
$ echo ${#name[@]}
4
$ echo ${#name[*]}
4
無下標的數組引用等價於引用其第0個元素
$ name=(2 3 4)
$ echo ${name}
2
銷燬
用unset
命令可以銷燬一個數組,也可以銷燬一個元素
# 銷燬整個數組
unset name
unset name[*]
# 銷燬一個元素
unset name[subscript]
擴展-漂移
獲取數組某個元素的長度,比如下面例子,world長度爲5
$ name=(hello world)
$ echo ${name[1]}
world
$ echo ${#name[1]}
5
數組元素漂移位置
$ echo ${name[1]:0} # 漂移量爲0
world
$ echo ${name[1]:1} # 漂移量爲1
orld
$ echo ${name[1]:3} # 漂移量爲3
ld
$ echo ${name[1]:6} # 超過元素長度,顯示空行
數組整體漂移位置
$ array=(one two three four five)
$ echo ${array[@]:0}
one two three four five
$ echo ${array[@]:1} # 漂移量爲1
two three four five
$ echo ${array[@]:1:2} # 量1,取2個
two three
擴展-匹配移除
數組元素匹配移除(以元素爲單位,針對所有元素)#
從左向右進行最短匹配##
從左向右進行最長匹配%
從右向左進行最短匹配%%
從右向左進行最長匹配
$ echo ${array[@]#t*e} # thre匹配移除
one two e four five
$ echo ${array[@]##t*e} # three匹配移除
one two four five
$ echo ${array[@]%r*e} # ree匹配移除
one two th four five
$ echo ${array[@]%%r*e} # ree匹配移除
one two th four five
擴展-替換
/xx/yy
對每個元素只替換一次//xx/yy
對每個元素替換多次//x/
刪除匹配內容
$ echo ${array[@]/e/E} # three第二個e沒替換
onE two thrEe four fivE
$ echo ${array[@]//e/E} # three第二個e沒替換
onE two thrEE four fivE
$ echo ${array[@]//e/} # 最大匹配刪除
on two thr four fiv
$ echo ${array[@]/e/} # 最小匹配刪除
on two thre four fiv
/#xx/yy
front-end匹配(從左向右)/%xx/yy
back-end匹配(從右向左)
$ echo ${array[@]/#o/O} # two的o沒替換
One two three four five
$ echo ${array[@]/%o/O} # one的o沒替換
one twO three four five
用函數替換
$ newstr() {
> echo -n “!!!”
> }
$ echo ${array[@]/%e/$(newstr)}
onXX two threXX four fivXX
擴展-添加元素
$ array=( “${array[@]}” “new1” )
$ echo ${array[@]}
one two three four five new1
$ array[${#array[@]}]=”new2”
$ echo ${array[@]}
one two three four five new1 new2
其他
read
命令支持以-a
參數從標準輸入讀入一個數組
$ read -a name
11 22 33
$ echo ${name[1]}
22