Looping through an array in shell script

Josh Sherman
1 min read
Command-line Interface Shell Script

Generally speaking, when I need to work with an array or dictionary type of variable, I tend to reach for something other than Bash / shell scripting.

This primarily stems from the fact that Bash didn’t support arrays until version 4.x and when I first learned about them, macOS (then OS X) was still shipping with version 3.x which didn’t support them.

Fast forwarded a few years, macOS is shipping with Z Shell and I am back to using Linux as my daily driver.

So all that said, even though I prefer to use a scripting language like JavaScript when I need more complex variables, there are times when I have an existing shell script that I’d rather not port over.

Let’s say you have a list of IP addresses you want to run through and run nmap against each one, first you’d define an array that looks something like this:

IP_ADDRESSES=(
  "192.168.0.1"
  "127.0.0.1"
  "192.168.1.1"
  "0.0.0.0"
)

Still weirds me out to define an array without a comma , between each item.

If you’re using Z Shell like I do, you can easily dump out the contents of the entire array using echo like it’s any other variable:

echo "$IP_ADDRESSES"

Which will display ll of the entries in the array, space delimited. With Bash, you’ll only get the first item of the array, sad face.

It doesn’t take much to loop through the items once the variable is defined:

for IP_ADDRESS in "${IP_ADDRESSES[@]}"; do
  # Swap `echo` for `nmap` to actually scan
  echo "$IP_ADDRESS"
done

Great, each IP address is displayed or you swapped echo for nmap and you’re waiting for the scan of each IP address to complete!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

Related Articles