linux Shell 命令行-03-array Shell 数组

拓展阅读

linux Shell 命令行-00-intro 入门介绍

linux Shell 命令行-02-var 变量

linux Shell 命令行-03-array 数组

linux Shell 命令行-04-operator 操作符

linux Shell 命令行-05-test 验证是否符合条件

linux Shell 命令行-06-flow control 流程控制

linux Shell 命令行-07-func 函数

linux Shell 命令行-08-file include 文件包含

linux Shell 命令行-09-redirect 重定向

定义

Shell 仅支持单维数组。

ini 复制代码
array=(值1 值2 ... 值n)
shell 复制代码
#!/bin/sh

# 数组演示
array=(a b "c" d)

# 另一种定义数组的方式

array_two[0]=a
array_two[1]=b
array_two[2]="c"
array_two[3]=d

读取

您可以这样从数组中读取:

bash 复制代码
${array_name[index]}
  • read_array.sh
shell 复制代码
#!/bin/sh

# 从数组中读取

array=(a b c "d")
echo "第一个元素是 ${array[0]}"
echo "第二个元素是 ${array[1]}"
echo "第三个元素是 ${array[2]}"
echo "最后一个元素是 ${array[-1]}"
  • 运行
shell 复制代码
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# chmod +x read_array.sh 
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# ./read_array.sh 
第一个元素是 a
第二个元素是 b
第三个元素是 c
最后一个元素是 d

读取所有元素

我们可以使用 *@ 来获取数组中的所有元素。

  • read_all_array.sh
shell 复制代码
#!/bin/sh
# 读取数组中的所有元素

array=(a b c d)
echo "数组中的所有元素:${array[*]}"
echo "数组中的所有元素:${array[@]}"
  • 运行
shell 复制代码
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# chmod +x read_all_array.sh 
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# ./read_all_array.sh 
数组中的所有元素:a b c d
数组中的所有元素:a b c d

数组长度

我们可以使用 ${#array[*]}${#array[@]} 来获取数组的大小。

  • array_length.sh
shell 复制代码
!#/bin/sh
# 数组长度

array=(a b c d E)
echo "数组的大小为:${#array[*]}"
echo "数组的大小为:${#array[@]}"
  • 运行
shell 复制代码
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# chmod +x array_length.sh 
root@iZuf60ahcky4k4nfv470juZ:~/code/shell# ./array_length.sh 
数组的大小为:5
数组的大小为:5

参考资料

www.runoob.com/linux/linux...

本文由博客一文多发平台 OpenWrite 发布!

相关推荐
ok!ko44 分钟前
设计模式之原型模式(通俗易懂--代码辅助理解【Java版】)
java·设计模式·原型模式
2402_857589361 小时前
“衣依”服装销售平台:Spring Boot框架的设计与实现
java·spring boot·后端
吾爱星辰2 小时前
Kotlin 处理字符串和正则表达式(二十一)
java·开发语言·jvm·正则表达式·kotlin
哎呦没2 小时前
大学生就业招聘:Spring Boot系统的架构分析
java·spring boot·后端
编程、小哥哥3 小时前
netty之Netty与SpringBoot整合
java·spring boot·spring
IT学长编程4 小时前
计算机毕业设计 玩具租赁系统的设计与实现 Java实战项目 附源码+文档+视频讲解
java·spring boot·毕业设计·课程设计·毕业论文·计算机毕业设计选题·玩具租赁系统
莹雨潇潇4 小时前
Docker 快速入门(Ubuntu版)
java·前端·docker·容器
杨哥带你写代码4 小时前
足球青训俱乐部管理:Spring Boot技术驱动
java·spring boot·后端
郭二哈5 小时前
C++——模板进阶、继承
java·服务器·c++
A尘埃5 小时前
SpringBoot的数据访问
java·spring boot·后端