shell中使用數組

1.  定義數組:

    可以有三種方法來定義一個數組:

    1)直接使用圓括號:

[root@test1 ~]# array1=(a b c d e f)

    2)通過在圓括號中指定下標來定義,默認下標從0開始:

[root@test1 ~]# array2=([0]='a0' [1]='a1' [2]='a2' [3]='a3')

    3)不使用圓括號,數組不用事先聲明:

[root@test1 ~]# array3[0]='b0'
[root@test1 ~]# array3[1]='b1'
[root@test1 ~]# array3[2]='b2'


2.  計算數組中的元素個數:

[root@test1 ~]# array=(a b c d e f)            ---- 首先定義一個數組
[root@test1 ~]# echo ${#array[@]}            ---- 兩種方式都可以獲取數組中元素的個數
或者
[root@test1 ~]# echo ${#array[*]}


3.  引用數組,獲取數組中的元素:

[root@test1 ~]# echo ${array[0]}               ---- 通過下標,獲取數組中的元素
[root@test1 ~]# echo ${array[1]}
[root@test1 ~]# echo ${array[10]}             ---- 指定的下標超過了數組的長度,返回空


4.  修改數組中的元素:

[root@test1 ~]# echo ${array[0]}
a
[root@test1 ~]# array[0]=a0
[root@test1 ~]# echo ${array[0]}
a0


5.  數組中添加元素:

[root@test1 ~]# echo ${array[6]}

[root@test1 ~]# array[6]=g
[root@test1 ~]# echo ${array[6]}
g


6.  遍歷數組:

[root@test1 ~]# for i in ${array[@]};do echo $i;done
a0
b
c
d
e
f
g


7.  刪除數組中的元素:

[root@test1 ~]# unset array[6]
[root@test1 ~]# for i in ${array[@]};do echo $i;done
a0
b
c
d
e
f
[root@test1 ~]# unset array
[root@test1 ~]# echo ${#array[@]}
0


8.  數組切片,獲取從指定下標開始的多個元素:

[root@test1 ~]# array1=([0]=a [1]=b [2]=c [3]=d [4]=e [5]=f)
[root@test1 ~]# echo ${array1[@]:1:3}               ---- 獲取從下標爲1開始的3個元素
b c d


9.  將字符串中的字母逐個放入數組,並輸出到“標準輸出”:

#!/bin/bash
chars='abcdefghijklmnopqrstuvwxyz'
for ((i=0;i<26;i++))
do
  array[$i]=${chars:$i:1}                 --- 注意此處的“chars”是字符串變量
  echo ${array[$i]}
done


10.  獲取本機所有TCP端口:

#!/bin/bash
port_arr=(`netstat -tnlp|awk {'print $4'}|awk -F':' '{if ($NF~/^[0-9]*$/) print $NF}'`)
length=${#port_arr[@]}
printf "{\n"
printf  '\t'"\"data\":["
for ((i=0;i<$length;i++))
 do
   printf '\n\t\t{'
   printf "\"{#TCP_PORT}\":\"${port_arr[$i]}\"}"
   if [ $i -lt $[$length-1] ];then
     printf ','
   fi
  done
printf  "\n\t]\n"
printf "}\n"


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章