Created
October 5, 2018 18:05
-
-
Save sjmcgrath/76f4fc595b8788d68cb862f41c053183 to your computer and use it in GitHub Desktop.
Bash Lessons: Arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ # Arrays... | |
$ | |
$ foo=( word 'this has spaces' ) | |
$ | |
$ # Unless you treat it like an array, | |
$ # it just behaves like a scalar with | |
$ # the first element of the array. | |
$ echo $foo | |
word | |
$ echo ${#foo} | |
$ 4 | |
$ | |
$ # Okay, let's treat it like an array. | |
$ echo ${#foo[*]} | |
2 | |
$ echo ${foo[*]} | |
word this has spaces | |
$ echo ${foo[@]} | |
word this has spaces | |
$ | |
$ # Hmm. Is there a difference between those? | |
$ for item in ${foo[*]}; do echo $item; done | |
word | |
this | |
has | |
spaces | |
$ for item in ${foo[@]}; do echo $item; done | |
word | |
this | |
has | |
spaces | |
$ | |
$ # Actually there is a difference, but you'll | |
$ # need quotes to see it. | |
$ for item in "${foo[*]}"; do echo $item; done | |
word this has spaces | |
$ for item in "${foo[@]}"; do echo $item; done | |
word | |
this has spaces | |
$ | |
$ # Arrays support appending as you might expect | |
$ foo+=( 'appended' ) | |
$ echo "${foo[@]}" | |
word this has spaces appended | |
$ | |
$ # You can index from the end too, | |
$ # but make sure you aren't off-by-one | |
$ echo ${foo[-1]} | |
appended |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment