linux 关联数组赋值,linux bash数组与关联数组简介

linux bash数组与关联数组:

数组包括普通数组与关联数组,普通数组只能用整数作为索引,关联数组可以使用字符或者字符串作为索引,4.0版本以上的bash才支持关联数组

1.普通数组:

定义数组:

[root@hexel ~]# array_test=(1 2 3 4 5)   --注意元素之间不能有逗号

打印数组元素:

[root@hexel ~]# echo ${array_test[0]}

1

[root@hexel ~]# echo ${array_test[4]}

5

全部打印:

[root@hexel ~]#  echo ${array_test[*]}

1 2 3 4 5

[root@hexel ~]#  echo ${array_test[@]} ---@方式是作为整体输出,而*方式是单个分别输出

1 2 3 4 5

打印数组长度:

[root@hexel ~]#  echo ${#array_test[@]}

5

数组中各个元素可以单独定义:

[root@hexel ~]# array_test1[1]="2"

[root@hexel ~]# array_test1[2]="3"

[root@hexel ~]# array_test1[4]="4"

[root@hexel ~]#  echo ${array_test1[3]}

[root@hexel ~]#  echo ${array_test1[4]}

4

2.关联数组:

关联数组需要4.0以上的bash支持

[root@hexel ~]# bash --version | grep release

GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)

定义关联数组:

首先需要声明一个变量,作为关联数组:

[root@hexel ~]# declare -A array_new

赋值:

同普通数组一样,关联数组可以使用内嵌(索引-值列表)方法赋值,也可以单独为元素赋值:

[root@hexel ~]# array_new=([egg]=10 [noodles]=20)

[root@hexel ~]# echo ${array_new[egg]}

10

[root@hexel ~]# echo ${array_new[noodles]}

20

其他使用方法和普通数组是一样的:

[root@hexel ~]# echo ${array_new[*]}

20 10

[root@hexel ~]# echo ${array_new[@]}

20 10

[root@hexel ~]# echo ${#array_new[@]}

2

此外,还可以打印数组索引列表:

[root@hexel ~]# echo ${!array_new[*]}

noodles egg

[root@hexel ~]# echo ${!array_new[@]}

noodles egg

关于@与*的区别,之前已经有文章介绍过了。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值