Shell Arrays

ShellShellBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to work with arrays in shell programming. Arrays allow you to store multiple values under one name, making it easier to organize and access data. You will learn how to initialize an array, add elements to it, access elements by their index, and determine the number of elements in the array.

Initialize an empty array

To start, let's create three empty arrays: NUMBERS, STRINGS, and NAMES. Open your editor and create a new shell script file called ~/project/arrays.sh. Add the following code to initialize the arrays:

#!/bin/bash

NUMBERS=()
STRINGS=()
NAMES=()

Add elements to the arrays

Now, let's add some elements to the arrays. Add the following code to add numbers 1, 2, and 3 to the NUMBERS array, and the words 'hello' and 'world' to the STRINGS array:

NUMBERS+=(1)
NUMBERS+=(2)
NUMBERS+=(3)

STRINGS+=("hello")
STRINGS+=("world")

Add names to the NAMES array

Let's add some names to the NAMES array. Add the following code to add the names 'John', 'Eric', and 'Jessica' to the NAMES array:

NAMES+=("John")
NAMES+=("Eric")
NAMES+=("Jessica")

Determine the number of names

To determine the number of names in the NAMES array, we can use the special variable $#. Add the following code to assign the length of the NAMES array to the NumberOfNames variable:

NumberOfNames=${#NAMES[@]}

Access the second name in the NAMES array

To access the second name in the NAMES array, we can use the brackets operator [ ]. Remember that array indices start at 0, so the second name would have an index of 1. Add the following code to assign the second name to the second_name variable:

second_name=${NAMES[1]}

Print the arrays and variables

Finally, let's print the arrays and variables to verify if everything is working correctly. Add the following code:

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"

Run the script

Save the arrays.sh file and open a terminal. Navigate to the directory where the script is located and run the following command to make the script executable:

chmod +x arrays.sh

Then, run the script using the following command:

./arrays.sh

You should see the following output:

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

Summary

Congratulations! You have successfully completed the Shell Programming Arrays Lab. You have learned how to initialize arrays, add elements to them, access elements by their index, and determine the number of elements in an array. Arrays are powerful tools that can help you organize and manipulate data in shell scripts.

Other Shell Tutorials you may like