Arrays and Looping Constructs in Shell Scripting

Introduction to Arrays and Looping Constructs in Shell Scripting

Hello! In this lesson, we will explore the powerful concepts of arrays and looping constructs in shell scripting. These are essential tools that will help you manage and manipulate data efficiently within your scripts. By the end of this lesson, you'll be able to handle arrays, iterate over their elements, and utilize different looping constructs to automate repetitive tasks.

Arrays allow you to store multiple items in a single variable, making it easier to handle lists of data. Looping constructs such as for and while loops enable you to execute a block of code multiple times, adding flexibility and power to your scripts.

Let's start our journey into arrays and looping constructs!

Syntax for Creating Arrays

In shell scripting, creating an array involves declaring a variable and assigning it multiple values enclosed in parentheses. Each value is separated by a space. Here’s the general syntax:

#!/bin/bash
computers=("Dell" "HP" "Lenovo")

You can add elements to an array using +=. For example:

#!/bin/bash
computers=("Dell" "HP" "Lenovo")
computers+=("Mac")

Now the array also includes the value "Mac".

Array Length and Printing

Array Indexing

Array indexing is the method of accessing individual elements in an array using their position, known as the index. Similar to other coding languages, the first element is at index 0. To access an element of an array use ${array_name[index_number]}. Let's take a look:

#!/bin/bash
computers=("Dell" "HP" "Lenovo")
echo "The first computer is: ${computers[0]}" 
echo "The second computer is: ${computers[1]}" 
echo "The third computer is: ${computers[2]}" 

The output of this script is:

"The first computer is: Dell"
"The second computer is: HP"
"The third computer is: Lenovo"

With this understanding of arrays, let's shift our focus to loops.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal