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

你可能感兴趣的:(学习,shell,脚本)