shell bash---类似数组类型

0 Preface/Foreword

C/C++,Python,Java等编程语言,都含有数组类型,那么shell脚本是不是也有类似的语法呢?

1 类似数组类型

1.1 ()类似数组类型

bash 复制代码
#! /bin/bash

echo "Welcome to bash world!"
animals=('cat' 'dog' 'horse' 'mouse')
#get a specified element
echo ${animals[0]}

#list all elements
echo ${animals[*]}
#list all elements
echo ${animals[@]}
#get the lenght of array
echo ${#animals[@]}
echo ${#animals[*]}

echo =================================
echo $#
echo $*
echo $@

echo ================================
echo $0
echo $1
echo $2
echo $?
echo =================================
echo $$
echo $!

++运行结果如下所示++:

分析:animals变量

  • 是一个数组类型,通过()来表示
  • 里面的元素只能是字符串
  • 字符串自己用空格分隔

1.1.1 获取数组中元素

通过下标index获取。

  • 第一个元素从++下标0开始++。
  • index越界了,不会报错,只是该变量为空。
  • 如果下标为空,则会报错。(bad substitution

1.1.2 获取数组元素列表

${arrayName[*]}

或者

${arrayName[@]}

1.1.3 获取数组长度

${**#**arrayName[@]}

或者

${**#**arrayName[*]}

1.2 遍历数组(for循环)

bash 复制代码
#! /bin/bash

echo "Welcome to bash world!"
animals=('cat' 'dog' 'horse' 'mouse')

echo "retrieve an array..."
count=0
for i in ${animals[*]}
do
	let count+=1
	echo "count is:"$count
done

运行结果:

相关推荐
岚天start1 天前
解决方案—K8S集群的日志按天并按照命名空间分类定时同步到日志服务器
服务器·docker·kubernetes·shell·日志备份
aitav03 天前
⚡ Linux awk 命令全面详解(包括记录、字段、命令空间)
linux·运维·服务器·bash·shell·awk
VincentHe7 天前
当 ServerCat 遇上 Shell 环境变量:一次服务器监控性能优化记录与探索
服务器·shell·监控
虚伪的空想家9 天前
ip网段扫描机器shell脚本
android·linux·网络协议·tcp/ip·shell·脚本·network
谅望者10 天前
Linux文件查看命令完全指南:cat、less、head、tail、grep使用详解
linux·excel·less·shell·文件操作·命令行·系统运维
hello_25012 天前
Shell脚本高效编写技巧
运维·shell
leaf9z13 天前
阿里云ECS在线扩容磁盘
阿里云·云计算·shell
gfdgd xi15 天前
deepin 终端,但是版本是 deepin 15 的
linux·python·架构·ssh·bash·shell·deepin
大米粥哥哥18 天前
Qt QProcess基于Linux的命令管道符号无效问题【已解决】
linux·qt·shell·qprocess·1024程序员节·管道符号
缘友一世24 天前
深入理解Shell与反弹Shell:从原理到实战
linux·网络安全·shell