Skip to content

Instantly share code, notes, and snippets.

@chanmix51
Last active April 2, 2020 18:26
Show Gist options
  • Save chanmix51/9a7fc8956f97ef5251331f1230dcbc0a to your computer and use it in GitHub Desktop.
Save chanmix51/9a7fc8956f97ef5251331f1230dcbc0a 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment