shell基础知识之数组
数组允许脚本利用索引将数据集合保存为独立的条目。Bash支持普通数组和关联数组,前者
使用整数作为数组索引,后者使用字符串作为数组索引。当数据以数字顺序组织的时候,应该使
用普通数组,例如一组连续的迭代。当数据以字符串组织的时候,关联数组就派上用场了,例如
主机名称。
普通数组
- 可以在单行中使用数值列表来定义一个数组
[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
分类:
linux-shell
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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语句:使用策略模式优化代码结构