Skip to content

Instantly share code, notes, and snippets.

@oplex
Forked from chanmix51/arrays_in_bash.md
Created April 2, 2020 18:26
Show Gist options
  • Save oplex/5cbdc20e69c970b3f7968a167fcf19ad to your computer and use it in GitHub Desktop.
Save oplex/5cbdc20e69c970b3f7968a167fcf19ad to your computer and use it in GitHub Desktop.
Using arrays in Bash

Using arrays in bash

creating an array

$> my_array=(one two three)

accessing/setting elements

$> echo ${my_array}
one
$> echo ${my_array[0]}
one
$> echo ${my_array[1]}
two
$> my_array[4]=five

dumping values

$> echo ${my_array[@]}
one two three five

dumping indices

$> echo ${!my_array[@]}
0 1 2 4

counting elements

$> echo ${#my_array[@]}
4

stringify array (return as one element)

$> echo ${my_array[*]}
one two three four

iterating on an array using index

$> for index in ${!my_array[@]}; do echo "Element N°${index} => ${my_array[$index]}"; done
Element N°0 => one
Element N°1 => two
Element N°2 => three
Element N°4 => five

iterating on an array extracting values

$> for element in ${my_array[@]}; do echo "Found element ${element}"; done
Found element one
Found element two
Found element three
Found element five

Store result in array, introduced bash 4.4

readarray -d '' array < <(find . -name "$input" -print0)
https://stackoverflow.com/a/54561526
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment