Interview Prep/Shell Scripting/Arrays, conditionals and loops

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops