[关闭]
@nrailgun 2016-06-22T14:52:46.000000Z 字数 562 阅读 1307

Array in shell programming

程序设计


Array: An array is a numbered list of strings: it maps integers to strings.

Creating arrays

With =() syntax.

  1. names=("John" "$USER")

Glob can also be used.

  1. files=(~/*'.jpg')

To list files

Do not use

  1. l=$(ls)
  2. l=($(ls))

Use

  1. l=(*)

Get element number

  1. echo ${#array[@]}

Expanding elements

We can use a for loop to iterate over the elements

  1. for i in "${l[@]}"; do
  2. echo "$i"
  3. done

We use the quoted form again here: "${l[@]}". Bash replaces this syntax with each element in the array properly quoted.

Use "${!l[@]}" to loop over the indices of arrays.

  1. for i in "${!l[@]}"; do
  2. echo "${l[i]}"
  3. done

Since it works with sparse array, it better than ${#l[@]}.

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注