在linux中定义数组的方法,shell中使用数组

流川枫海 2021-05-15 22:39:41 

文章标签: 在linux中定义数组的方法

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

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"

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值