shell脚本之数组

194 阅读1分钟

如何创建数组

字符串和字符串列表

字符串:123456789
字符串列表:"10 20 30 40 50"
数组(10 20 30 40 50) 每个元素的分隔符一定是空格
      0  1  2  4  5

数组的创建方法

方法一
数组名=(数组内容)
echo ${数组名[@]} ##可以将整个数组内容全部列出来
echo ${数组名[*]} ##作用和上面一样
echo ${数组名[下标序号]} ##将数组的一部分列出来

image.png

方法二
数组名="数组内容"

image.png

数组名=([0]=10 [1]=20 [2]=30 [3]=40

image.png

数组名[0]=10

image.png

image.png

数据类型

数值类型
字符类型
当用字符类型时记得用""'' 来定义

获取数组长度

echo ${#数组名[@]}

image.png

数组分片

image.png

数组替换

这是数组的临时替换 image.png

image.png

删除数组

image.png

image.png

添加数组

方法一
array_name[index]=value

image.png

方法二
arry[${#arry[@]}]=50

image.png

方法三
arry=("${arry[@]}" "10" "20")

image.png

方法四
arry+=(10 20)

image.png

查看所有的数组

declare -a

image.png

将数组的值传给参数

  • 第一步:向函数传入数组的时候需要先把数组转换成列表作为函数的参数使用:  函数名 ${数组名1[@]}  
  • 第二步:在函数内把传入的列表重新组合成数组:  数组名2=($@)  
  • 第三步:在函数外重新组合成数组:  数组名3=(函数名 ${数组名1[@]})

用for循环将数组的所有值相加求和

image.png

image.png

用for循环将数组的所有值乘2

image.png

image.png