当前位置:网站首页>Shell脚本-数组定义以及获取数组元素
Shell脚本-数组定义以及获取数组元素
2022-07-01 08:36:00 【小蜗牛的路】
数组的定义
用括号( )来表示数组,数组元素之间用空格来分隔
nums=(v1 v2 v3 v4 ... vn)
注意,赋值号=两边不能有空格,必须紧挨着数组名和数组元素。
此外,你也无需逐个元素地给数组赋值,下面的代码就是只给特定元素赋值:
ages=([3]=24 [5]=19 [10]=12)
以上代码就只给第 3、5、10 个元素赋值,所以数组长度是 3。
获取数组元素
一般使用下面的格式:
${array_name[index]}
n=${nums[2]} #表示获取 nums 数组的第二个元素,然后赋值给变量 n。
echo ${nums[3]} #表示输出 nums 数组的第 3 个元素。
使用@或*可以获取数组中的所有元素,例如:
${nums[*]}
${nums[@]}
两者都可以得到 nums 数组的所有元素。
代码如下
#!/bin/bash
nums=(29 100 13 8 91 44)
echo ${nums[@]} #输出所有数组元素
nums[10]=66 #给第10个元素赋值(此时会增加数组长度)
echo ${nums[*]} #输出所有数组元素
echo ${nums[4]} #输出第4个元素
输出:
29 100 13 8 91 44
29 100 13 8 91 44 66
91
获取数组长度
利用@或*,可以将数组扩展成列表,然后使用#来获取数组元素的个数
${#array_name[@]}
${#array_name[*]}
代码如下:
#!/bin/bash
nums=(29 100 13)
echo ${#nums[*]}
#向数组中添加元素
nums[10]="http://c.biancheng.net/shell/"
echo ${#nums[@]}
echo ${#nums[10]}
#删除数组元素
unset nums[1]
echo ${#nums[*]}
输出:
3
4
29
3
边栏推荐
猜你喜欢

ARM v7的体系结构A、R、M区别,分别应用在什么领域?

为什么LTD独立站就是Web3.0网站!

"Analysis of 43 cases of MATLAB neural network": Chapter 30 design of combined classifier based on random forest idea - breast cancer diagnosis

大型工厂设备管理痛点和解决方案

【无标题】

Share 7 books I read in the first half of 2022

《微机原理》—总线及其形成

Intelligent constant pressure irrigation system

What is the material of 16MnDR, the minimum service temperature of 16MnDR, and the chemical composition of 16MnDR

FreeRTOS learning easy notes
随机推荐
公网集群对讲+GPS可视追踪|助力物流行业智能化管理调度
Nacos - service discovery
【无标题】
[deep analysis of C language] - data storage in memory
Matlab [function derivation]
避免按钮重复点击的小工具bimianchongfu.queren()
Advanced level of C language pointer (Part 1)
软件工程师面试刷题网站、经验方法
R语言入门
The era of low threshold programmers is gone forever behind the sharp increase in the number of school recruitment for Internet companies
Nacos - 配置管理
C语言指针的进阶(上篇)
"Analysis of 43 cases of MATLAB neural network": Chapter 30 design of combined classifier based on random forest idea - breast cancer diagnosis
Matlab tips (23) matrix analysis -- simulated annealing
NIO-零拷贝
[MFC development (17)] advanced list control list control
Properties of 15MnNiNbDR low temperature vessel steel, Wugang 15MnNiDR and 15MnNiNbDR steel plates
In depth learning training sample amplification and tag name modification
5mo3 UHI HII HII 17mn4 19Mn6 executive standard
内存大小端