Shell数组

来源:互联网 发布:mysql 数据库撞库工具 编辑:程序博客网 时间:2024/06/05 18:14

1.Shell数组的定义

1.1空数组定义

#define a null arraynull_arr=()null_arr[0]=testnull_arr[1]=2echo ${null_arr[1]}  $null_arr#2 test

注意:
  1. 如果直接打印数组名$null_arr,那么只会输出数组的第一个元素,
  2. 数组元素的数据类型可以不同。

1.2非空数组定义

#define a array with 5 elementsarr=(1 2 3 4 5)

注意:数组元素是以“ ”(空格符)隔开,而不是“,”(逗号)。

2.数组的长度

#calculate the length of the arraylen=${#arr[@]}echo "Length of array: $len"#Length of array: 5

3.数组的遍历

3.1用像C语言中的for遍历

不过,用这种方式需要计算数组的长度。
#traverse the array with C-forfor ((i = 0; i < len; i++));do{    echo $i"th element: ${arr[i]}"}done#0th element: 1#1th element: 2#2th element: 3#3th element: 4#4th element: 5

3.2用下标索引遍历

#traverse the array with its indexfor i in "${!arr[@]}";do{    echo $i"th element: ${arr[i]}"}done#0th element: 1#1th element: 2#2th element: 3#3th element: 4#4th element: 5

3.3直接访问元素

#traverse the array with forfor val in ${arr[@]};do{    echo $val       }done#1#2#3#4#5

3.4while-do遍历

#traverse the array with whilei=0while [ $i -lt ${#arr[@]} ];do{    echo $i"th element: ${arr[i]}"    #i=$(($i + 1))    #let ++i    let i++}done#0th element: 1#1th element: 2#2th element: 3#3th element: 4#4th element: 5

如果只是打印数组的话,可以用下面的快捷方式,注意${arr[*]}和${arr[@]}是等价的。
echo "My array: ${arr[*]}"echo "My array: ${arr[@]}"

4.shell数组的特色

shell数组的特色

  1. shell数组可以给任何位置赋值,而未被赋值的位置是空(没有任何元素,包括空格等)。
  2. shell数组的长度不受定义时的长度限制。
  3. shell数组的长度指的是数组中元素的个数。并且对第一条仍然适用,即空位置不算长度。
  4. shell数组中元素类型可以不同。

arr[10]=testecho "current length of the array: ${#arr[@]}"echo "8th and 9th elements of the array are: ${arr[8]}, ${arr[9]}"echo "10th element of the array: ${arr[10]}"#current length of the array: 6#8th and 9th elements of the array are: , #10th element of the array: test


完整代码:

#!/usr/bin/env bash#define a null arraynull_arr=()null_arr[0]=testnull_arr[1]=2echo ${null_arr[1]} $null_arr#define a array with 5 elementsarr=(1 2 3 4 5)#calculate the length of the arraylen=${#arr[@]}echo "Length of array: $len"#traverse the array with C-forfor ((i = 0; i < len; i++));do{echo $i"th element: ${arr[i]}"}done#traverse the array with its indexfor i in "${!arr[@]}";do{echo $i"th element: ${arr[i]}"}done#traverse the array with forfor val in ${arr[@]};do{echo $val}done#traverse the array with whilei=0while [ $i -lt ${#arr[@]} ];do{echo $i"th element: ${arr[i]}"#i=$(($i + 1))#let ++ilet i++}donearr[10]=testecho "current length of the array: ${#arr[@]}"echo "8th and 9th elements of the array are: ${arr[8]}, ${arr[9]}"echo "10th element of the array: ${arr[10]}"




0 0
原创粉丝点击