Arrays in Linux shell scripting

For a script I want to build for maintaining WordPress themes & plugins a bit easier I wanted to basically loop through a list of locations of WordPress installations on a single server. This basically means I need to be able to create an “array”.

I knew that you could use arrays in a shell script as I was using it in another script to automatically make a backup of all databases in a MySQL or PostgreSQL database, however that script gets the list from the output of an application: how do you define them yourself?

First thing to know is that array support differs by which shell you use. I prefer simply “/bin/sh”, but that only has extremely basic array support. Bash (and others) have better support. Fortunately the array support in “/bin/sh” is sufficient in my case.

Anyway, on to the solution. In “/bin/sh” you define an array as a list of strings separated by spaces (as such, I’m not sure if you can include strings with spaces) and use a very simple “for” loop to iterate through them:

#!/bin/sh

ARRAY="Hello World"

for WORD in $ARRAY
do
  echo $WORD
done

This script will display each word from the array on a different line. Note that there is no way to refer to a specific member of the array (you can’t use an index).

In Bash you can use arrays in a more advanced way:

#!/bin/bash

ARRAY=("Hello" "World")
ARRAY[2]="In Bash"
LENGTH=${#ARRAY[@]}

for ((i = 0; i < $LENGTH; i++))
do
  echo ${ARRAY[i]}
done

Now as you can see you can easily define a list of strings (with spaces if you want), refer to specific members of the array using an index and get the length of the array.

2 thoughts on “Arrays in Linux shell scripting

  1. hi,
    i want to find out how many times a particular character in the content of an array is coming..
    regards

    1. Hmm. I’m not an expert in shell programming but I think that is easier to do in a small script in PHP/Python/Perl or whatever. Just replace #!/bin/sh with whatever you want to use (ie: #!/usr/bin/php to execute a PHP script from shell).