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

运行结果:

相关推荐
析数塔12 小时前
把 shell 历史结构化:Atuin 18.21.0 的数据模型、加密同步与工程取舍
shell·aiops
金銀銅鐵5 天前
如何统计当前目录下所有 java 文件的总行数?
shell
柒号华仔9 天前
「速通Shell」Shell 编程性能优化
shell
lingran__9 天前
Linux 基础常用指令万字详解(下)|一切皆文件:重定向、管道、日志 与 Shell 原理
linux·运维·服务器·shell·管道·重定向·打包压缩
yanlaifan11 天前
Shell编程---shell bash中的keyword
shell
柒号华仔12 天前
「速通Shell」常用命令(下)—— 归档、权限与进阶工具
shell
柒号华仔13 天前
「速通Shell」常用命令(中)——进程、网络与系统信息
shell
YuSun_WK13 天前
shell脚本
shell·脚本
柒号华仔17 天前
「速通Shell」Shell 脚本测试详解
shell
柒号华仔18 天前
「速通Shell」Shell 脚本模块化
shell