Bash Arrays: Difference between revisions

From NovaOrdis Knowledge Base
Jump to navigation Jump to search
Line 29: Line 29:


==Assignment==
==Assignment==
===Individual Elements===


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


  a[0]="something"
  a[0]="something"
===Entire Array===


==Reference==
==Reference==

Revision as of 21:49, 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

Assignment

Individual Elements

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

a[0]="something"

Entire Array

Reference

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.

Use Cases

Associative Arrays