How do you declare, populate and iterate an indexed array?
BeginnerConceptArrays, conditionals and loops
Answer
hosts=(web1 web2 "web 3")
hosts+=(web4) # append
echo "${hosts[0]}" # first element
echo "${#hosts[@]}" # number of elements: 4
for h in "${hosts[@]}"; do # quoted: "web 3" stays one element
echo "deploying to $h"
done
echo "${!hosts[@]}" # indices: 0 1 2 3
echo "${hosts[@]:1:2}" # slice: web2 web 3
unset 'hosts[1]' # remove element (indices are now sparse)
Always iterate with "${arr[@]}". ${arr} alone is just element 0, a common bug.
More on Arrays, conditionals and loops
What is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?IntermediateList the most-used file test operators.Beginner