shell-array

shell-array

 Creating Array:

1  $ names=("Bob" "Peter" "$USER" "Big Bad John")
2  $ names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")
3  # or...
4  $ names[0]="Bob"

You can get the number of elements of an array by using ${#array[@]}:

1 $ array=(a b c)
2 $ echo ${#array[@]}
3 3

There is also a second form of expanding all array elements, which is "${arrayname[*]}". This form is ONLY useful for converting arrays into a single string with all the elements joined together. The main purpose for this is outputting the array to humans:

1 $ names=("Bob" "Peter" "$USER" "Big Bad John")
2 $ echo "Today's contestants are: ${names[*]}"
3 Today's contestants are: Bob Peter lhunath Big Bad John

Associative Arrays

 To create an associative array, you need to declare it as such (using declare -A).

1 $ declare -A fullNames
2 $ fullNames=( ["lhunath"]="Maarten Billemont" ["greycat"]="Greg Wooledge" )
3 $ echo "Current user is: $USER.  Full name: ${fullNames[$USER]}."
4 Current user is: lhunath.  Full name: Maarten Billemont.

 参考:

  1. http://hi.baidu.com/gaogaf/item/46050b15958a5225f7625c4a

  2. http://www.cnblogs.com/chengmo/archive/2010/09/30/1839632.html

  3. http://bash.cumulonim.biz/BashGuide(2f)Arrays.html

  

原文地址:https://www.cnblogs.com/tekkaman/p/3059884.html