shell基础知识之数组

数组允许脚本利用索引将数据集合保存为独立的条目。Bash支持普通数组和关联数组,前者
使用整数作为数组索引,后者使用字符串作为数组索引。当数据以数字顺序组织的时候,应该使
用普通数组,例如一组连续的迭代。当数据以字符串组织的时候,关联数组就派上用场了,例如
主机名称。

普通数组

  1. 可以在单行中使用数值列表来定义一个数组
[root@dns-node2 tmp]# array_var=(test1 test2 test3)
[root@dns-node2 tmp]# echo ${array_var[0]}
test1

另外,还可以将数组定义成一组“索引-值”

[root@dns-node2 tmp]# array_var[0]="test0"
[root@dns-node2 tmp]# array_var[0]="test3"
[root@dns-node2 tmp]# array_var[2]="test2"
[root@dns-node2 tmp]# array_var[3]="test0"
[root@dns-node2 tmp]# echo ${array_var}
test3
[root@dns-node2 tmp]# echo ${array_var[3]}
test0
[root@dns-node2 tmp]# echo ${array_var[2]}
test2
[root@dns-node2 tmp]# echo ${array_var[1]}
test2
[root@dns-node2 tmp]# echo ${array_var[0]}
test3

打印这个数组下面所有的值

[root@dns-node2 tmp]# echo ${array_var[*]}
test3 test2 test2 test0
[root@dns-node2 tmp]# echo ${array_var[@]}
test3 test2 test2 test0

打印数组的长度

[root@dns-node2 tmp]# echo ${#array_var[@]}
4

关联数组

在关联数组中,我们可以用任意的文本作为数组索引。首先,需要使用声明语句将一个变量,这个其实是Map,在python里面叫做字典,在go里面叫做map。
定义为关联数组

使用行内“索引-值”列表:
[root@dns-node2 tmp]# declare -A ass_array
[root@dns-node2 tmp]# ass_array=([i1]=v1 [i2]=v2)
使用独立的“索引-值”进行赋值
[root@dns-node2 tmp]# ass_array=[i1]=v1
[root@dns-node2 tmp]# ass_array=[i2]=v2

取值

[root@dns-node2 tmp]# echo ${ass_array[i1]}
v1
[root@dns-node2 tmp]# echo ${ass_array[i2]}
v2
[root@dns-node2 tmp]# echo ${ass_array[*]}  # 取value
v2 v1
[root@dns-node2 tmp]# echo ${ass_array[@]}  # 取value
v2 v1
[root@dns-node2 tmp]# echo ${!ass_array[@]}   #取key
i2 i1

posted @   温柔易淡  阅读(161)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示