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

运行结果:

相关推荐
花落已飘3 天前
STM32中实现shell控制台(命令解析实现)
stm32·shell
Johny_Zhao4 天前
Docker 一键安装部署 JumpServer 堡垒机
linux·网络安全·信息安全·云计算·shell·jumpserver·ldap·yum源·系统运维
Johny_Zhao4 天前
Ubuntu系统安装部署Pandawiki智能知识库
linux·mysql·网络安全·信息安全·云计算·shell·yum源·系统运维·itsm·pandawiki
bcbobo21cn5 天前
初步了解Linux etc/profile文件
linux·运维·服务器·shell·profile
1.01^100017 天前
[2-02-02].第59节:功能函数 - 函数基础
shell
___波子 Pro Max.18 天前
Shell脚本中&&和||语法解析
shell
lewis_lk21 天前
文本处理三剑客: grep、sed、awk使用指南
后端·shell
Johny_Zhao22 天前
企业级LDAP-RADIUS深度集成高可用方案
linux·网络·python·网络安全·信息安全·云计算·shell·cisco·系统运维
Johny_Zhao22 天前
基于CentOS Stream 8的物联网平台深度优化方案
linux·网络·网络安全·信息安全·云计算·shell·yum源·系统运维
Johny_Zhao23 天前
CentOS Stream 8 高可用 Kuboard 部署方案
linux·网络·python·网络安全·docker·信息安全·kubernetes·云计算·shell·yum源·系统运维·kuboard