ZSH is a powerful shell interpreter with a wide surface for customization. One of the most powerful features of ZSH is its scripting language that allows you to build powerful tools and automation tasks.
In this tutorial, we will explore the various looping and iteration techniques available in ZSH and discover some usage of these techniques.
Loops and iterators are one of the most fundamental building blocks in any programming language. If you want to enhance your scripting skills, we highly recommend you to master them.
That being said, let’s dive in!
ZSH Loops
Loops play a crucial role in functional and efficient programs and scripts. No matter which language you choose, you are bound to encounter a form of looping construct. ZSH is no different.
Using loops, we can allow a block of code to run until a specific condition is met. A major use of loops includes iterating through dictionaries, lists, or even performing the batch array operations within a script.
ZSH Looping Constructs
1. “For” Loops
The first and most common looping construct across the programming languages is the “for” loop. In ZSH, a “for” loop allows us to iterate over a sequence of items such as numbers, words, or elements in an array.
An example syntax is as follows:
do
# Loop body
done
In this case, we start with the “for” keyword, followed by the individual item in the sequence. We then proceed to provide the sequence that we wish to iterate.
Next, we create a loop body denoted by the “do” keyword. In here, we provide the logic for the loop and all the operations that we wish to loop to carry out.
Finally, we use the “done” keyword to close the loop body.
Example 1:
The following example demonstrates how to use a “for” loop to iterate over a sequence of numbers from 1 to 5:
do
echo "Iteration $i"
done
This should print the numbers from 1 to 5: 1, 2, 3, 4, 5.
Example 2:
We can also use a “for” loop to iterate over the items of an array as demonstrated in the following example code:
databases=("MySQL" "PostgreSQL" "SQLite" "Redis" "Elasticsearch")
# Iterate through the array using a for loop
for db in "${databases[@]}"
do
echo "Database: $db"
done
Output:
Database: PostgreSQL
Database: SQLite
Database: Redis
Database: Elasticsearch
2. “While” Loop
The second loop construct is the “while” loop. As the name probably suggests, a “while” loop executes a block of code as long as a specified condition is true.
The syntax for a “while” loop in ZSH is as follows:
do
# Loop body
done
In this case, we define the condition that we wish to evaluate. This condition must return a Boolean value, either true or false.
Example:
Take for example the following code that demonstrates how to use a basic “for” loop to perform a countdown:
while [ $count -gt 0 ]
do
echo "Countdown: $count"
((count--))
done
You will notice the “count—“ operation. This is used to ensure that in each iteration, the value decrements by 1 which leads to the condition becoming true at some point. If you do not specify this condition, the loop continues to run as it never becomes false. This is also known as an “infinite” loop.
3. “Until” Loop
We also have a loop construct which is known as “until” loop. An “until” loop is extremely similar to a “while” loop. But unlike a “for” loop, it continues the execution as the condition is false.
It is basically an inverse of an “until” loop.
The syntax for the “until” loop is as follows:
do
# Loop body
done
Example:
The following example shows how to use an “until” loop to wait until a given task is complete:
do
sleep 1
done
echo "Process $pid has finished."
The previous loop terminates the process with the specified process. It keeps sleeping for one second until the termination is complete.
-
Conditionals
We can also utilize the control structure such as “if”, “elif”, and “else” within a given loop to add a more conditional logic. This makes the loops more complex and extensible to handle a wider and more granular execution.
Example:
The following code block demonstrates how we can incorporate the conditional statements into a loop to perform a task when a given task is true/false:
do
if [ -f "$file" ]
then
echo "Processing file: $file"
# Perform some action
else
echo "Skipping non-file: $file"
fi
done
We can also use the loops to process all the files in a given directory by combining them with glob patterns as demonstrates in the following example:
do
echo "Processing file: $file"
# Perform some action
done
4. Nested loops
Nested loops are basically loops that are within another loop. When you need to perform a recursive and more complex operations, a “nested” loop can be your aid.
Be careful when using “nested” loops since there is a potential of either no action performing or an action occurring recursively and infinitely.
An example of a “nested” loop is as follows:
do
for j in {A..C}
do
echo "$i$j"
done
done
There you have it!
Conclusion
In this ZSH scripting lesson, we taught you everything you need to know when it comes to working with loops and iterators in ZSH scripting. We learned things such as “for” loops, “while” loops, “until” loops, “nested” loops, conditionals, and more. We also showed you how to iterate the sequences and more.