当前位置:网站首页>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
边栏推荐
- Do you know how data is stored? (C integer and floating point)
- [MFC development (17)] advanced list control list control
- The era of low threshold programmers is gone forever behind the sharp increase in the number of school recruitment for Internet companies
- There are many problems in sewage treatment, and the automatic control system of pump station is solved in this way
- Dynamic proxy
- Centos7 shell脚本一键安装jdk、mongo、kafka、ftp、postgresql、postgis、pgrouting
- [MFC development (16)] tree control
- Brief introduction to AES
- 基础:3.opencv快速入门图像和视频
- 《单片机原理及应用》—定时器、串行通信和中断系统
猜你喜欢
随机推荐
Advanced level of C language pointer (Part 1)
Screenshot tips
Advanced API
避免按钮重复点击的小工具bimianchongfu.queren()
DID的使用指南,原理
Serial port to WiFi module communication
I would like to know the process of stock registration and account opening by mobile phone? In addition, is it safe to open a mobile account?
分享2022上半年我读过的7本书
What is the material of 16mo3 steel plate? What is the difference between 16mo3 and Q345R?
【面试必刷101】链表
如何一站式高效管理固定资产?
Qt的模型与视图
factory type_ Id:: create process resolution
Shell脚本-位置参数(命令行参数)
Glitch free clock switching technology
Mavros sends a custom topic message to Px4
C语言指针的进阶(下)
《单片机原理及应用》-片外拓展
Intelligent water conservancy solution
3、Modbus通讯协议详解









