Shell编程学习之数组的使用

数组

Shell编程中数组的特点:

  • 只有一维数组
  • 小括号'()'表示;
  • 不需要定义,且没有类型;
  • 在脚本文件中,默认数组的成员都是字符串

数组初始化格式:

#方式1:
A1=(welcome "tobeijing" 'and' giveme 555)
#方式2
A2=([0]="hello" [2]="henan" [4]="fine")

引用数组各个成员的值:

echo ${A1[0]}
echo ${A1[1]}
echo ${A1[2]}
echo ${A1[3]}
echo ${A1[4]}
echo "~~~~~~~~~~~~~~~"
echo ${A2[0]}
echo ${A2[1]}
echo ${A2[2]}
echo ${A2[3]}
echo ${A2[4]}

对数组成员重新赋值:

  • 数组名[下标]=“字符串”

测试案例一:

A1[0]="thank"

引用数组的各个成员:

  • ${数组名[@]} OR ${数组名[*]}

测试案例二:

echo ${A1[@]}
echo ${A2[*]}

计算数组成员的个数:

  • ${#数组名[@]} OR ${#数组名[*]}

测试案例三:

echo ${#A1[@]}
echo ${#A2[*]}

对数组的追加需要的字符串:

 A1=(Hi ${A1[@]})
 A2=(${A2[*]} Nice)

测试代码:

#!/bin/bash


#方式1:
A1=(welcome "tobeijing" 'and' giveme 555)
#方式2
A2=([0]="hello" [2]="henan" [4]="fine")

echo ${A1[0]}
echo ${A1[1]}
echo ${A1[2]}
echo ${A1[3]}
echo ${A1[4]}
echo "~~~~~~~~~~~~~~~"
echo ${A2[0]}
echo ${A2[1]}
echo ${A2[2]}
echo ${A2[3]}
echo ${A2[4]}


A1[0]="thank"

echo ${A1[@]}
echo ${A2[*]}

echo ${#A1[@]}
echo ${#A2[*]}

A1=(hi ${A1[@]})

A2=(${A2[*]} Nice)

echo ${A1[@]}
echo ${A2[*]}
echo ${#A1[@]}
echo ${#A2[*]}

运行结果:

welcome
tobeijing
and
giveme
555
~~~~~~~~~~~~~~~
hello

henan

fine
thank tobeijing and giveme 555
hello henan fine
5
3
hi thank tobeijing and giveme 555
hello henan fine Nice
6
4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值