Arrays in Shell Scripting
Store many values in a single Bash variable, read them by index, count them, and loop over all of them with a for loop.
A normal variable holds one value. That is fine for one name or one number. But automation scripts usually deal with a group of things: a list of servers to deploy to, a list of services to check, a list of files to back up. Creating server1, server2, server3 as three separate variables works for three servers and becomes unmanageable at thirty.
An array is one variable that holds many values. Every programming language has the concept, and Bash has it too.
Creating an array
Write the values inside parentheses, separated by spaces:
car=("BMW" "Audi" "Tesla")Three rules to remember:
- No space around
=, the same as for any variable. - The values are separated by spaces, not commas.
("BMW", "Audi")would storeBMW,with the comma as part of the value. - Put each value in quotes. It is required as soon as a value contains a space, and it is a good habit in every other case.
You can try all the commands of this section directly in the terminal. No script is needed yet.
Reading from an array
Each value in an array has a position number, called its index. The index starts at 0, not at 1.
To read a value, use ${name[index]}:
echo ${car[0]}
echo ${car[1]}
echo ${car[2]}BMW
Audi
TeslaIn the lecture, ${car[1]} is typed while talking about the "first" element, and the output is Audi. That is the index rule in action: index 1 is the second value. The first value is always at index 0.
All the values
Use @ in place of the index:
echo ${car[@]}BMW Audi TeslaHow many values
Add a # before the name:
echo ${#car[@]}3Why the curly braces matter
With arrays the braces are not optional. See what happens without them:
echo $car[1]BMW[1]Bash read $car alone, which gives the first value, and then printed [1] as plain text. Always write ${car[1]}.
Asking for an index that does not exist is not an error. It gives an empty value:
echo ${car[5]}Looping over an array
Reading values one by one with their index is fine for three values. The real strength of an array is that a loop can walk through all of it, however long it is. You have already seen the for loop in Loops in Shell Scripting. Here it gets a list to work on.
vi arrays.sh#!/bin/bash
cars=("BMW" "Audi" "Tesla")
for car in ${cars[@]}
do
echo $car
donechmod u+x arrays.sh
./arrays.shBMW
Audi
TeslaWhat happens step by step:
${cars[@]}expands to all the values:BMW Audi Tesla.- The loop takes the first value,
BMW, and stores it in the variablecar. - The commands between
doanddonerun. Here it is only anecho, but it can be any work you want to do with that value. - The loop goes back, takes the next value,
Audi, puts it incarand runs the body again. - The same for
Tesla. When no values are left, the loop ends.
Note the two names: cars is the array, car is the single value of the current round. Any names work, but plural for the array and singular for the loop variable makes a script easy to read.
A DevOps example
Replace the cars with something you would really loop over, a list of servers:
#!/bin/bash
servers=("server1" "server2" "server3")
for server in ${servers[@]}
do
echo "App Deployed on $server"
done./arrays.shApp Deployed on server1
App Deployed on server2
App Deployed on server3The script only prints a message, but the shape is the same as a real deployment script. Replace the echo with an ssh or scp command and the same loop does the job on every server. To add a fourth server, you add one word to the array. Nothing else in the script changes.
Quote the array in a loop
The lecture writes ${cars[@]} without quotes. It works there because none of the values contains a space. Try a value that does:
#!/bin/bash
servers=("web server" "db server")
for server in ${servers[@]}
do
echo "Checking $server"
doneChecking web
Checking server
Checking db
Checking serverFour rounds for two values. Without quotes, Bash splits every value again at the spaces. Put the whole expansion in double quotes and each value stays in one piece:
for server in "${servers[@]}"Checking web server
Checking db serverMake "${array[@]}" with the quotes your default. It is always correct, with or without spaces in the values.
Changing an array
The lecture creates arrays and reads them. In real scripts you will also need to change them:
car=("BMW" "Audi" "Tesla")
car+=("Kia") # add a value at the end
car[1]="Volvo" # replace the value at index 1
echo ${car[@]}
echo ${#car[@]}BMW Volvo Tesla Kia
4Quick reference
| Syntax | Meaning | Result for car=("BMW" "Audi" "Tesla") |
|---|---|---|
${car[0]} | First value | BMW |
${car[1]} | Second value | Audi |
${car[-1]} | Last value | Tesla |
${car[@]} | All values | BMW Audi Tesla |
${#car[@]} | Number of values | 3 |
${!car[@]} | All the indexes | 0 1 2 |
car+=("Kia") | Add a value at the end | |
car[1]="Volvo" | Replace one value | |
unset car[1] | Remove one value |
Arrays need Bash
Arrays are a Bash feature. The plain sh shell does not have them. If you run the script as sh arrays.sh, you get Syntax error: "(" unexpected on Ubuntu, even though the first line says #!/bin/bash. Run it as ./arrays.sh or bash arrays.sh.
Try It Yourself
- In the terminal, create
car=("BMW" "Audi" "Tesla")and print the first value, the last value, all values and the count. - Run
echo $car[1]andecho ${car[1]}and explain the difference in the output. - Create
arrays.shwith theserversarray and the loop. Add a fourth server and run it again. - Change one server name to
"web server"and run the loop with and without quotes around${servers[@]}. - Write
services.shwith an array("nginx" "ssh" "cron")that printsChecking <service>for each one. You will turn this into a real status check in the automation lessons.
Official references
Written By: Shramik Masti
How is this guide?
Last updated on
Environment Variables in Linux
Create your own environment variables with export, make them permanent for one user with ~/.bashrc, and make them available to every user with /etc/profile.
Case Statement in Shell Scripting
Replace long if-elif chains with the Bash case statement, match a value against several patterns, and handle everything else with a default branch.
