Bash Array

最後更新: 2023-11-21

目錄

  • 定義 Array (Explicit / Indirect)
  • Access element in array
  • * 與 @
  • Basic Usage
  • Iterate through an array
  • Array as command Args

Bash 的 Array

Bash 支援以下兩種 Array

  • One-dimensional indexed(integers) array
  • Associative array

Array 的限制:

  • No maximum limit on the size of an array
  • No requirement that members be indexed or assigned contiguously

 


定義 Array (Explicit / Indirect)

 

Explicit declaration of an array

Indexed array

declare -a arrayname

# Associative arrays

declare -A arrayname

Indirect declaration

arrayname[index]=value

# Arrays are assigned to using compound assignments of the form

[1]

arrayname[0]="value0"
arrayname[1]="value1"
arrayname[2]="value2"

[2]

A)

arrayname=(value0 value1 value3)

B)

arrayname=(
  A 
  B 
  C
)

 

 


Access element in array

 

# Any element of an array may be referenced using

${arrayname}                            # 相當於 "${arrayname[0]}"

 

${arrayname[index]}

 * The braces are required to avoid conflicts with the shell’s filename expansion operators

 


* 與 @

 

# These subscripts differ only when the word appears within double quotes

  • "${name[*]}"
  • "${name[@]}"

# '@' expands each element of name to a separate word (for loop 時用它 !!)

# '*' expands to a single word with the value of each array member separated by the first character of the IFS variable

LIST=(1 2 3)
for i in "${LIST[*]}"; do # 相當於 "1 2 3"
  echo "$i"               # result: 1 2 3,
done
for i in "${LIST[@]}"; do
  echo "$i"               # result: 一行一個數字
done

 


Basic Usage

 

# Length

${#arrayname[@]}                     # The length of arrary

${#arrayname[index]}          # The length of ${name[subscript]}

 

# Extraction by offset and length

${Unix[@]:3:2}

 

# Copying an Array

Linux=("${Unix[@]}")

 

# Add an element

Unix=("${Unix[@]}" "AIX" "HP-UX")

 

# Concatenation

UnixShell=("${Unix[@]}" "${Shell[@]}")

 

# Load Content of a File into an Array

#!/bin/bash
filecontent=( `cat "logfile" `)

for t in "${filecontent[@]}"
do
    echo $t
done

 

# unset

unset name                      # removes the entire array

unset name[subscript]      # destroys the array element at index subscript.

 


Iterate through an array

 

#!/bin/bash

# arrayname=( A B C )
# 這樣寫好看點
arrayname=( 
  A 
  B 
  C
)
 
for m in "${arrayname[@]}"
do
  echo "${m}"
done

 


Array as command Args

 

rsync_options=( -rnv --exclude='.*' )

rsync "${rsync_options[@]}" source/ target

remark

"..."   # 是必需的

 


 

 

 

 

Creative Commons license icon Creative Commons license icon