miscellaneous_tips:20_software_development:bash_notes:bash_arrays

'bash' Arrays

#!/bin/bash

# Declare associatice array directly:
declare -A array=(
  [foo_1]='bar_1'
  [foo_2]='bar_2'
)

# And/or declare indiviual array members:
array[bar_1]='foo_x'
array[bar_2]='foo_y'

# The keys are accessed using an exclamation point: ${!array[@]},
# the values are accessed using ${array[@]}.
# You can iterate over the key/value pairs like this:

for i in "${!array[@]}"
do
  echo "key: $i, value: ${array[$i]}"
done

Using an array for a list of file names has the advantage that it's not a problem if path/file names contain spaces.

#!/bin/bash

# Declare an indexed array with file names:

declare -a files=(
  '/'
  '/etc'
  '~/my subdir'
)

for file in "${files[@]}"; do
  # Enclose variables in double quotes for proper expansion
  echo "${file}"
done

Martin Burnicki martin.burnicki@burnicki.net 2019-03-06

  • miscellaneous_tips/20_software_development/bash_notes/bash_arrays.txt
  • Zuletzt geändert: 2021-01-26 17:14
  • von martin