shell中同样有数组的概念,获取数组中的元素要使用下标[],并且下标的值必须大于等于0。数据的各项特性见下例:
#!/bin/bash
array1=(1 2 3 999)
echo ${array1[3]}
array2=(1 3 5 "hello,world") # different data type
echo ${array2[0]}
echo ${array2[3]}
array1[4]=1000 # append more data
echo ${array1[4]}
echo ${array2[*]} # print all data from data array
echo ${array2[@]}
注意,赋值号两边一定不能出现空格!
获取数组的长度
#!/bin/bash
arr=(1 2 "hello")
echo ${#arr[*]} # print 3
echo ${#arr[@]} # print 3
echo ${#arr[2]} # print 5
拼接数组
#!/bin/bash
arr1=(1 2 3)
arr2=("hello" "world" 3 2 1)
arr_new1=(${arr1[*]} ${arr2[*]})
arr_new2=(${arr1[@]} ${arr2[@]})
echo ${arr_new1[*]}
echo ${arr_new2[@]}
输出
1 2 3 hello world 3 2 1
1 2 3 hello world 3 2 1
数组的删除
#!/bin/bash
arr=(1 2 3)
unset arr[1]
echo ${arr[*]} # print 1 3
arr[1]=4
echo ${arr[*]} # print 1 4 3
unset arr
echo ${arr[*]} # print nothing