Like most programming languages, bash scripts sometimes need to deal with a list of related values. The simplest form is the standard array.

In bash, array programming is quite different, in particular when it comes to syntax. Bash arrays are also strictly one-dimensional, but they still have plenty of uses.

The Basic Syntax of Bash Arrays

Creating an array in bash is straightforward. You can initialize an entire array using brackets, for example:

        city=(London Paris Milan "New York")
    

(You can find all the code from this city example in this GitHub Gist.)

This creates an array containing four elements, indexed from 0 to 3. Note that the fourth value is a quoted string consisting of two words. You’ll need to quote values containing spaces to clarify that they aren’t separate values.

You can access a single element using the bracket syntax that’s common across programming languages:

        city[2]
    

Since this is bash, you’ll need a couple of refinements to actually use the value in an expression:

  • You’ll need to prepend the dollar sign ($) to the variable name.
  • You’ll also need to use braces ({}) to make the variable name unambiguous. By default, bash will treat $city[2] as a variable named city. Add braces to tell bash to evaluate the brackets and index number too.

The standard bash array access syntax is then:

        ${variable_name[index]}
    

Here’s a complete example:

        #!/bin/bash
    
city=(London Paris Milan "New York")
echo ${city[3]}
    
# New York

Instead of initializing an array all at once, you can assign to it step-by-step. This script is a longer equivalent of the previous example:

        #!/bin/bash
    
city[0]=London
city[1]=Paris
city[2]=Milan
city[3]="New York"
echo ${city[3]}
   
# New York

Note that, in either case, you need to be careful not to add any space around the equals sign. “city[0] = London”, with spaces around the equals sign, will generate an error.

More Uses for Bash Arrays

Arrays are perfect for storing related data. Here’s a (very limited) shell script to get the square root of a number:

        #!/bin/bash
    
sqrt[1]=1
sqrt[4]=2
sqrt[9]=3
sqrt[16]=4
sqrt[25]=5
    
echo ${sqrt[$1]}

Note that the script uses the value $1 as the array index. $1 represents the first command-line argument the script receives, so you can run this script like so:

        $ ./sqrt.sh 9
3

You may be aware of the $(cmd) syntax to execute a command and save its output in a variable. You can combine this with the array initialization syntax to get an array of files to work with:

        arr=( $(ls) )
    

An array is often a perfect data structure for iterating and Bash is no exception. You might loop through an array to print every element or to perform an operation on every member.

You can address an array in a for .. in loop, to iterate over its contents. For example, here’s a simple loop that prints the number of lines in each file in the array arr:

        for file in "${arr[@]}"; do
    wc -l "$file"
done
    
# 3 envvars
# 547 httpd.conf
# ...

Note that this pattern makes use of the @ symbol to retrieve all elements from the array.

More Bash Array Syntax

You can get the number of items in an array using the following:

        echo ${#city[@]}
    
# 4

You can add a new element onto the end of a standard array like so:

        arr+=(4)
    

So to add a fifth city to the list:

        city+=(Rome)
echo ${city[@]}
    
# London Paris Milan New York Rome

To extract a chunk of an array, you can use a syntax that approximates the slice operation of many other languages:

        ${arr[@]:s:n}
    

This syntax will return a slice of the array beginning at position s and containing n items. You can omit the :n part to extract all items from s until the end of the list.

        echo ${city[@]:2:2}
# Milan New York
    
echo ${city[@]:3}
# New York Rome

Bash Has Many Features, They Just Take Some Learning

Arrays in bash may have limitations, but they offer the same basic functionality as most programming languages do. Although bash has historically supported just straightforward one-dimensional arrays, times are changing. The latest version of bash, 4, supports associative arrays and negative array indexing.

Whichever version of bash you’re using, it’s important to understand its nuances. Even normal variable syntax has plenty of idiosyncrasies.