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!
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:
You can add elements to an array using +=. For example:
Now the array also includes the value "Mac".
Often you need to find the length of an array or print out all of its contents.
You can access the length of an array using ${#array_name[@]}. To print the contents of an array use ${array_name[@]}. Let's take a look:
${#computers[@]}accesses the number of elements using the${#array_name[@]}syntax${computers[@]}accesses all the elements of the array using the${array_name[@]}syntax.
This script prints out
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:
The output of this script is:
With this understanding of arrays, let's shift our focus to loops.
The while loop in shell scripting allows you to execute a block of code repeatedly as long as a given condition is true. It’s useful for cases where the number of iterations is not known beforehand and depends on certain conditions. The syntax structure of a while loop is:
conditionis a test expression that is evaluated before each iteration. The loop continues as long as this condition is true.- The
do...doneblock contains the commands to be executed as long as the condition is true.
Let's look at an example:
counter=1creates a variable namedcounteris initialized to 1. This variable will control the number of iterations in the loop.while [ $counter -le 3 ]: Thewhileloop starts with the condition[ $counter -le 3 ]. The loop will continue to execute as long as the value ofcounteris less than or equal to (-le) 3.domarks the start of the block of commands to run for each iteration
The for loop in shell scripting allows you to iterate until a condition is met. It’s commonly used to automate repetitive tasks by executing a block of code multiple times. The syntax of a for loop is:
-
initialization: This sets the starting value for the loop control variable. It is executed only once at the beginning of the loop. -
condition: This is a boolean expression. The loop continues to execute as long as this condition is true. It is evaluated before each iteration. -
update: This operation updates the loop control variable after each iteration of the loop. -
do: This keyword indicates the beginning of the block of commands that will be executed in each iteration of the loop. -
commands: These are the commands or code that will be executed each time the loop iterates. -
done: This keyword marks the end of the loop block. After executing the commands, control goes back to theupdatestep and the condition is checked again. If the condition is true, the loop runs again; otherwise, it terminates.
Here’s a simple example to illustrate the syntax:
- The loop control variable
xis initialized to 1, and the loop continues as long as is less than or equal to 3. The variable is incremented by 1 after each iteration.
The for in loop in shell scripting allows you to iterate over a sequence of values or elements. The syntax of a for loop is:
variableis a loop control variable that takes the value of each element in the list one by one.listcan be a sequence of numbers, strings, or an array.- The
do...doneblock contains the commands to be executed in each iteration.
Let's see a concrete example looping over a range of numbers. A range is defined as {start..end}. Unlike some coding languages, end is inclusive. Let's take a look:
for i in {1..5}: The loop control variableitakes values from 1 to 5.do ... done: This specifies the block of code to run for each iterationecho "Iteration $i": Prints the current iteration number.
The output of the above script is:
Combining arrays and loops, you can iterate over array elements by combining for in with "${array_name[@]}". Here's an example:
for computer in "${computers[@]}": Theforloop starts with the control variablecomputer.do ... done: The code inside this block is run during each iteration.echo "$computer": The loop prints the current value of the$computervariable from thecomputersarray
The output of the script is:
Great job! In this lesson, you've learned the fundamentals of arrays and looping constructs in shell scripting. You now know how to declare and access arrays, use for loops and while loops, and iterate over array elements.
These skills are crucial for automating tasks and handling complex data in your scripts. Arrays allow you to manage multiple items efficiently, while loops enable you to perform repetitive tasks seamlessly.
Now, it's time to apply what you've learned! Proceed to the practice section to reinforce your understanding with hands-on exercises. Get ready to enhance your scripting skills further. Happy coding!
