Shell数组

1.Shell数组的定义

1.1空数组定义

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

#2 test

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

1.2非空数组定义

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

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

2.数组的长度

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

#Length of array: 5

 
 

3.数组的遍历

3.1用像C语言中的for遍历

不过,用这种方式需要计算数组的长度。
#traverse the array with C-for
for ((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 index
for 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 for
for val in ${arr[@]};do
{
    echo $val       
}
done

#1
#2
#3
#4
#5

 
  

3.4while-do遍历

 
  
#traverse the array with while
i=0
while [ $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]=test
echo "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 array
null_arr=()
null_arr[0]=test
null_arr[1]=2
echo ${null_arr[1]} $null_arr
#define a array with 5 elements
arr=(1 2 3 4 5)
#calculate the length of the array
len=${#arr[@]}
echo "Length of array: $len"
#traverse the array with C-for
for ((i = 0; i < len; i++));do
{
echo $i"th element: ${arr[i]}"
}
done
#traverse the array with its index
for i in "${!arr[@]}";do
{
echo $i"th element: ${arr[i]}"
}
done
#traverse the array with for
for val in ${arr[@]};do
{
echo $val
}
done
#traverse the array with while
i=0
while [ $i -lt ${#arr[@]} ];do
{
echo $i"th element: ${arr[i]}"
#i=$(($i + 1))
#let ++i
let i++
}
done
arr[10]=test
echo "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]}"



 
 

你可能感兴趣的:(linux,shell,数组)