Shell Arrays

ShellShellBeginner
Practice Now

Introduction

In this lab, you will learn how to work with arrays in shell programming. Arrays are data structures that allow you to store multiple values under a single name, making it easier to organize and manipulate data. You will learn how to initialize arrays, add elements to them, access elements by their index, and determine the number of elements in an array. This knowledge is fundamental for more advanced shell scripting and data manipulation tasks.

Create a new shell script file

Let's start by creating a new shell script file where we'll write our array operations.

  1. Open your terminal in the WebIDE.

  2. Navigate to the project directory:

    cd ~/project
  3. Create a new file named arrays.sh using the touch command:

    touch arrays.sh
  4. Open the arrays.sh file in the WebIDE.

Initialize empty arrays

Now that we have our script file, let's start by initializing three empty arrays.

Add the following code to your arrays.sh file:

#!/bin/bash

## Initialize empty arrays
NUMBERS=()
STRINGS=()
NAMES=()

Let's break down what this code does:

  • The first line #!/bin/bash is called a shebang. It tells the system that this script should be executed by the Bash shell.
  • We're creating three empty arrays: NUMBERS, STRINGS, and NAMES.
  • The () syntax initializes an empty array.

Add elements to the arrays

Now that we have our empty arrays, let's add some elements to them.

Add the following code to your arrays.sh file, below the array initializations:

## Add elements to NUMBERS array
NUMBERS+=(1)
NUMBERS+=(2)
NUMBERS+=(3)

## Add elements to STRINGS array
STRINGS+=("hello")
STRINGS+=("world")

## Add elements to NAMES array
NAMES+=("John")
NAMES+=("Eric")
NAMES+=("Jessica")

Here's what this code does:

  • We use the += operator to append elements to our arrays.
  • For NUMBERS, we're adding the integers 1, 2, and 3.
  • For STRINGS, we're adding the words "hello" and "world".
  • For NAMES, we're adding three names: "John", "Eric", and "Jessica".
  • Note that we enclose string elements in quotes, but numbers don't need quotes.

Determine the number of elements in an array

One common operation with arrays is finding out how many elements they contain. Let's do this for our NAMES array.

Add the following code to your arrays.sh file:

## Get the number of elements in the NAMES array
NumberOfNames=${#NAMES[@]}

This line does the following:

  • ${#NAMES[@]} gives us the number of elements in the NAMES array.
  • We store this value in a variable called NumberOfNames.
  • The @ symbol inside the brackets refers to all elements of the array.
  • The # symbol before NAMES tells the shell to count the elements.

Access a specific element in an array

Now, let's access a specific element in our NAMES array. We'll get the second name.

Add this code to your arrays.sh file:

## Access the second name in the NAMES array
second_name=${NAMES[1]}

Here's what this code does:

  • We're accessing the second element of the NAMES array with ${NAMES[1]}.
  • Remember, array indices in Bash start at 0, so [1] gives us the second element.
  • We store this value in a variable called second_name.

Print the arrays and variables

Finally, let's add some code to print out our arrays and variables to see the results of our operations.

Add the following code to the end of your arrays.sh file:

## Print the arrays and variables
echo "NUMBERS array: ${NUMBERS[@]}"
echo "STRINGS array: ${STRINGS[@]}"
echo "The number of names listed in the NAMES array: $NumberOfNames"
echo "The second name on the NAMES list is: $second_name"

This code does the following:

  • We use echo to print strings to the console.
  • ${NUMBERS[@]} and ${STRINGS[@]} print all elements of these arrays.
  • We print the NumberOfNames and second_name variables we created earlier.

Run the script

Now that we've written our script, it's time to run it and see the results.

  1. In your terminal, make sure you're in the correct directory:

    cd ~/project
  2. Make the script executable:

    chmod +x arrays.sh
  3. Run the script:

    ./arrays.sh

You should see output similar to this:

NUMBERS array: 1 2 3
STRINGS array: hello world
The number of names listed in the NAMES array: 3
The second name on the NAMES list is: Eric

This output shows that our array operations were successful:

  • The NUMBERS array contains 1, 2, and 3.
  • The STRINGS array contains "hello" and "world".
  • We correctly counted 3 names in the NAMES array.
  • We successfully retrieved "Eric" as the second name.

Summary

In this lab, you've learned the fundamentals of working with arrays in shell scripting. You've practiced initializing arrays, adding elements to them, accessing specific elements, and determining the number of elements in an array. These skills are crucial for more advanced shell scripting tasks, especially when dealing with lists of data or when you need to perform operations on multiple items. Arrays provide a powerful way to organize and manipulate data in your shell scripts, making your code more efficient and easier to manage.

Other Shell Tutorials you may like