1. 程式人生 > >bash shell 中數組使用舉例

bash shell 中數組使用舉例

腳本 erro 一個 結果 背景 pen done modify follow

bash shell 中數組使用舉例

一 背景

讓我們先來看一個 shell 腳本的執行過程及結果:

[[email protected] ~]$ sh array.sh N2 N3 N4
The elements of this array 2-4 are: N2 N3 N4
N1 is in array.  
N2 is in array.  
N3 is in array.  
N4 is in array.  
The original array is as follows: N1 N2 N3 N4
The length of this array is 4. 
The array[2] is N3. 
Append an element at the end of this array. This array: N1 N2 N3 N4 N5
Modify an element in an array. This array: N1 N2 N6 N4 N5

二 實現

實現腳本如下:

#!/bin/bash
array=(‘N1‘ ‘N2‘ ‘N3‘ ‘N4‘)
case $1 in 
  ${array[0]})
    echo "${array[0]}"
  ;;
  ${array[@]:1:3})
    echo "The elements of this array 2-4 are: ${array[@]:1:3}"
  ;;
  *)
    echo "ERROR"
  ;;
esac
for num in ${array[@]} ;do
   echo "${num} is in array. "
done
echo "The original array is as follows: ${array[@]}"
echo "The length of this array is ${#array[*]}. "
echo "The array[2] is ${array[2]}. "
array[${#array[@]}]=N5
echo "Append an element at the end of this array. This array: ${array[@]}"
array[2]=N6
echo "Modify an element in an array. This array: ${array[*]}"

三 總結

3.1 這個例子實現了數組的各種用法,我們可以通過執行結果進行直觀理解。需要註意的是子數組的獲取,元素的修改,追加。
3.2 shell 數組的使用與其他編程語言有所不同,可以類比理解。

bash shell 中數組使用舉例