Create a Array

  1. $ a[0]=foo
  2. $ echo ${a[0]}
  1. #!/bin/bash
  2. declare -a a
  1. $ days=(Sun Mon Tue Wed Thu Fri Sat)
  1. $ days=([0]=Sun [1]=Mon [2]=Tue [3]=Wed [4]=Thu [5]=Fri [6]=Sat)

Any reference to an array variable without a subscript refers to element zero of the array.

Array Operations

Array Contents

${a[*]}
${a[@]} — the most useful
The subscripts * and @ can be used to access every element in an array.

  1. $ animals=("a dog" "a cat" "a fish")
  2. $ for i in ${animals[*]}; do echo $i; done
  3. a
  4. dog
  5. a
  6. cat
  7. a
  8. fish
  9. $ for i in ${animals[@]}; do echo $i; done
  10. a
  11. dog
  12. a
  13. cat
  14. a
  15. fish
  16. $ for i in "${animals[*]}"; do echo $i; done
  17. a dog a cat a fish
  18. $ for i in "${animals[@]}"; do echo $i; done
  19. a dog
  20. a cat
  21. a fish

Array Length

${#a[@]}

  1. $ echo ${#a[@]} # number of array elements
  2. 1
  3. $ echo ${#a[100]} # length of element 100
  4. 3

Finding the Subscripts Used by an Array

${!array[*]}
${!array[@]} — the most useful

  1. $ foo=([2]=a [4]=b [6]=c)
  2. $ for i in "${foo[@]}"; do echo $i; done
  3. a
  4. b
  5. c
  6. $ for i in "${!foo[*]}"; do echo $i; done
  7. 246
  8. $ for i in "${!foo[@]}"; do echo $i; done
  9. 2
  10. 4
  11. 6

Adding Elements to the End of an Array

a+=(v1 v2 v3)

  1. $ foo=(a b c)
  2. $ echo ${foo[@]}
  3. a b c
  4. $ foo+=(d e f)
  5. $ echo ${foo[@]}
  6. a b c d e f

Sorting an Array

  1. #!/bin/bash
  2. # array-sort: Sort an array
  3. a=(f e d c b a)
  4. echo "Original array: ${a[@]}"
  5. a_sorted=($(for i in "${a[@]}"; do echo $i; done | sort))
  6. echo "Sorted array: ${a_sorted[@]}"
  1. $ array-sort
  2. Original array: f e d c b a
  3. Sorted array: a b c d e f

Deleting an Array

unset a —— delete array
unset 'a[1]' —— delete element of array

The array element must be quoted to prevent the shell from performing pathname expansion.

  1. $ echo ${foo[@]}
  2. a b c d e f
  3. $ unset foo
  4. $ echo ${foo[@]}
  5. $
  6. $ foo=(a b c d e f)
  7. $ echo ${foo[@]}
  8. a b c d e f
  9. $ unset 'foo[2]'
  10. $ echo ${foo[@]}
  11. a b d e f

Associative Arrays

Associative arrays use strings rather than integers as array indexes.

Unlike integer indexed arrays, which are created by merely referencing them, associative arrays must be created with the declare command using the new -A option.

bash versions 4.0 and greater support associative arrays.

  1. #!/bin/bash
  2. declare -A colors
  3. colors["red"]="#ff0000"
  4. colors["green"]="#00ff00"
  5. colors["blue"]="#0000ff"
  6. echo ${colors["blue"]}