After reading up on how to initialize arrays in Bash, and seeing some basic examples put forward in blogs, there remains some uncertainties on its practical use. An interesting
There are a few cases where I like to use arrays in Bash.
When I need to store a collections of strings that may contain spaces or $IFS
characters.
declare -a MYARRAY=(
"This is a sentence."
"I like turtles."
"This is a test."
)
for item in "${MYARRAY[@]}"; do
echo "$item" $(echo "$item" | wc -w) words.
done
This is a sentence. 4 words. I like turtles. 3 words. This is a test. 4 words.
When I want to store key/value pairs, for example, short names mapped to long descriptions.
declare -A NEWARRAY=(
["sentence"]="This is a sentence."
["turtles"]="I like turtles."
["test"]="This is a test."
)
echo ${NEWARRAY["turtles"]}
echo ${NEWARRAY["test"]}
I like turtles. This is a test.
Even if we're just storing single "word" items or numbers, arrays make it easy to count and slice our data.
# Count items in array.
$ echo "${#MYARRAY[@]}"
3
# Show indexes of array.
$ echo "${!MYARRAY[@]}"
0 1 2
# Show indexes/keys of associative array.
$ echo "${!NEWARRAY[@]}"
turtles test sentence
# Show only the second through third elements in the array.
$ echo "${MYARRAY[@]:1:2}"
I like turtles. This is a test.
Read more about Bash arrays here. Note that only Bash 4.0+ supports every operation I've listed (associative arrays, for example), but the link shows which versions introduced what.