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

运行结果:

相关推荐
波特率1152001 小时前
bash命令进阶学习(Shell 元字符)
linux·bash·shell
阿常呓语10 小时前
Linux命令 jq详解
linux·运维·shell·jq
buhuimaren_18 小时前
Shell循环语句
shell
IMPYLH1 天前
Bash 的 basenc 命令
linux·运维·服务器·bash·shell
IMPYLH2 天前
Linux 的 base64 命令
linux·运维·服务器·bash·shell
IMPYLH2 天前
Linux 的 base32 命令
linux·运维·服务器·bash·shell
一乐小哥2 天前
同样用 Claude Code,为什么别人的终端比你好看又好用?
shell
一乐小哥2 天前
Zsh 与 Bash 配置文件:用法、区别、迁移
macos·shell
liulilittle2 天前
解决 liburing 编译时缺失 `linux/time_types.h` 的问题
linux·运维·服务器·ubuntu·shell
liulilittle2 天前
Ubuntu 系统 libc6-dev 依赖冲突解决
linux·运维·服务器·ubuntu·shell