您的位置:首页 > 运维架构 > Shell

shell中使用数组

2018-10-23 15:52 411 查看

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"


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数组 shell