標籤:shell 數組
定義數組
a=(1 2 3 4 5 6)
列印數組
echo ${a[@]} 或者 echo ${a[*]}
[[email protected] shell]# a=(1 2 3 4 5 6)[[email protected] shell]# echo ${a[@]}1 2 3 4 5 6[[email protected] shell]# echo ${a[*]}1 2 3 4 5 6
通過下標列印數組中的元素
[[email protected] shell]# echo ${a[0]}1[[email protected] shell]# echo ${a[1]}2[[email protected] shell]# echo ${a[2]}3[[email protected] shell]# echo ${a[3]}4[[email protected] shell]# echo ${a[4]}5[[email protected] shell]# echo ${a[5]}6[[email protected] shell]# echo ${a[6]}[[email protected] shell]# echo ${a[7]}[[email protected] shell]#
擷取數組元素的個數
echo ${#a[@]}
[[email protected] shell]# echo ${#a[@]}6
數組的賦值 存在則替換 不存在則增加 【通過下標來定位】
[[email protected] shell]# a[6]=100[[email protected] shell]# echo ${a[@]}1 2 3 4 5 6 100[[email protected] shell]# a[6]=aa[[email protected] shell]# echo ${a[@]}1 2 3 4 5 6 aa
數組刪除元素 【通過下標來定位】
[[email protected] shell]# unset a[6][[email protected] shell]# echo ${a[@]}1 2 3 4 5 6[[email protected] shell]# unset a[[email protected] shell]# echo ${a[@]}[[email protected] shell]#
數組的切片
[[email protected] shell]# b=(`seq 1 10`)[[email protected] shell]# echo ${b[@]}1 2 3 4 5 6 7 8 9 10[[email protected] shell]# echo ${b[@]:3:4} #從下標為三的元素開始截取 截取4個4 5 6 7[[email protected] shell]# echo ${b[@]:0-3:2} #從下標為倒數第三的元素開始截取 截取2個8 9
數組元素的替換
[[email protected] shell]# echo ${b[@]}1 2 3 4 5 6 7 8 9 10[[email protected] shell]# echo ${b[@]/3/33} #只在顯示結果裡替換元素 數組不變1 2 33 4 5 6 7 8 9 10[[email protected] shell]# echo ${b[@]/7/77} #只在顯示結果裡替換元素 數組不變1 2 3 4 5 6 77 8 9 10[[email protected] shell]# echo ${b[@]}1 2 3 4 5 6 7 8 9 10
[[email protected] shell]# b=(${b[@]/8/888}) #改變數組組成元素[[email protected] shell]# echo ${b[@]}1 2 3 4 5 6 7 888 9 10
shell中的數組