Bash Arrays: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 75: Line 75:
  ${#var_name[@]}
  ${#var_name[@]}
  ${#var_name[*]}
  ${#var_name[*]}
{{Warn|If the array is sparse, this does not return the index of last element plus one, but just the number of non-empty elements}}


==Iterate==
==Iterate==

Revision as of 22:37, 23 February 2018

Internal

Indexed Arrays

External

Overview

bash indexed arrays are 0-based and unidimensional. No explicit declaration is necessary if at least one element is initialized as described below:

Declaration

Arrays do not need explicit declarations, they will be automatically declared upon the first assignment of any of their elements:

my_array_var[0]="something"

They can be explicitly declared, though:

declare -a my_array_var

Previously declared arrays can be listed with:

declare -a

An array variable can be "undeclared" with the "unset" builtin.

unset my_array_var

Individual array elements can also be unset:

unset my_array_var[subscript] 

A subscript of "*" or "@" also removes the entire array.

Assignment

Assign Individual Elements

Individual elements are initialized by using ${var-name[index]}=value notation:

a[0]="something"

Entire Array

The (...) syntax can be used to initialize an entire array. The values must be separated by space:

a=("X" "Y" "Z")

If we want initialize only specific elements, we can use this syntax:

a=([0]="X" [4]="Y" [8]="Z")

Reference

Reference Individual Elements

Element arrays can be referenced with ${var-name[index]} notation:

echo ${a[0]}

If the array variable was not previously declared, or if the specific element was not initialized, a reference attempt will return the blank string.

Reference All Elements

${var_name[@]}
${var_name[*]}

Length

${#var_name[@]}
${#var_name[*]}

If the array is sparse, this does not return the index of last element plus one, but just the number of non-empty elements

Iterate

Using the Index

i=0
while [[ ${i} < ${#x[@]} ]]; do
  echo ${x[$i]}
  ((i++))
done

Use Cases

Read the Content of a File into An Array

Each line will be assigned to an element of the array:

readarray < ./somefile.txt -t my_array_var

Assign Words Read from stdin to an Array

Assing words read from stdin to an array:

read -a

Iterate Over the Argument List

args=("$@")
for arg in ${args[@]}; do
  ...
done

Associative Arrays