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

运行结果:

相关推荐
虚伪的空想家2 天前
ip网段扫描机器shell脚本
android·linux·网络协议·tcp/ip·shell·脚本·network
谅望者3 天前
Linux文件查看命令完全指南:cat、less、head、tail、grep使用详解
linux·excel·less·shell·文件操作·命令行·系统运维
hello_2505 天前
Shell脚本高效编写技巧
运维·shell
leaf9z6 天前
阿里云ECS在线扩容磁盘
阿里云·云计算·shell
gfdgd xi8 天前
deepin 终端,但是版本是 deepin 15 的
linux·python·架构·ssh·bash·shell·deepin
大米粥哥哥11 天前
Qt QProcess基于Linux的命令管道符号无效问题【已解决】
linux·qt·shell·qprocess·1024程序员节·管道符号
缘友一世17 天前
深入理解Shell与反弹Shell:从原理到实战
linux·网络安全·shell
hour_go19 天前
Linux Shell 实验一:数据采集与脚本调试错误总结
linux·笔记·bash·shell·实验报告·错误排查
struggle202520 天前
AxonHub 开源程序是一个现代 AI 网关系统,提供统一的 OpenAI、Anthropic 和 AI SDK 兼容 API
css·人工智能·typescript·go·shell·powershell
shark22 天前
无需放弃变更、关闭占用程序!用暂存区和 git底层命令实现 Git 变更备份
git·shell·自动化运维