declare -a array_name
數組
array_name[xx]=value
array_name=([xx]=value1 [yy]=value2 ...)
array_name=(value1 value2 value3 ...)
或declare -a array_name=(value1 value2 value3 ...)
array=( "${array[@]}" "new element" )
或array[${#array[*]}]="new element"
函數
array2=( "${array1[@]}" )
或array2="${array1[@]}"
code
${array_name[xx]}
${array_name[@]}
或${array_name[*]}
"${array_name[@]}"
表示單獨的數組元素,"${array_name[*]}"
表示數組元素總體,沒有引號括起的狀況下都表示單獨的數組元素,相似$*
和$@
的區別 ${array_name[@]:index:length}
獲取連續的部分數組元素,其中:length
可省略。three
arrayZ=( one two three four five ) # 提取全部元素 echo ${arrayZ[@]:0} # one two three four five # 提取下標從1開始(包含)的全部元素 echo ${arrayZ[@]:1} # two three four five # 提取下標從1開始(包含)的2個元素 echo ${arrayZ[@]:1:2} # two three
${#array_name[*]}
或${#array_name[@]}
element
${#array_name[xx]}
字符串
${array_name[xx]:index:length}
, 其中:length可省略co
unset array_name[xx]
array_name[xx]=
unset array_name
一般狀況下,形如${name...}
表示法的字符串操做均可以應用在數組上,使用${name[@]...}
或${name[*]...}
的方式。字符
子字符串移除數字
arrayZ=( one two three four five five ) # 從每一個元素的最左側進行最短匹配,並刪除匹配的字符串 echo ${arrayZ[@]#fiv} # one two three four e e echo ${arrayZ[@]#t*e} # one two e four five five # 從每一個元素的最左側進行最長匹配,並刪除匹配的字符串 echo ${arrayZ[@]##t*e} # one two four five five # 從每一個元素的最右側進行最短匹配,並刪除匹配的字符串 echo ${arrayZ[@]%h*e} # one two t four five five # 從每一個元素的最右側進行最長匹配,並刪除匹配的字符串 echo ${arrayZ[@]%%t*e} # one two four five five
子字符串替換new
arrayZ=( one two three four fivefive fivefive ) # 對每一個元素進行字符串匹配,並替換第一次匹配的字符串 echo ${arrayZ[@]/fiv/XYZ} # one two three four XYZefive XYZefive # 對每一個元素進行字符串匹配,並替換全部匹配的字符串 echo ${arrayZ[@]//fiv/XYZ} # one two three four XYZeXYZe XYZeXYZe # 對每一個元素進行字符串匹配,並刪除全部匹配的字符串 echo ${arrayZ[@]//fi/} # one two three four veve veve # 從每一個元素的最左側進行最長匹配,並替換匹配的字符串 echo ${arrayZ[@]/#f*v/XYZ} # one two three four XYZe XYZe # 從每一個元素的最右側進行最長匹配,並替換匹配的字符串 echo ${arrayZ[@]/%i*e/XYZ} # one two three four fXYZ fXYZ # 其餘用法:函數的標準輸出做爲要替換的字符串 replacement() { echo -n '!!!' } echo ${arrayZ[@]/%e/$(replacement)} # on!!! two thre!!! four fivefiv!!! fivefiv!!!