zsh

Zsh Scripting Lesson: Understanding Conditional Statements and Control Structures

In this post, we will talk about conditional statements and control constructs in Zsh scripting. Conditional statements and control structures are a powerful tool and major building blocks in building extensible and efficient applications.

Basic Conditional Statements

Conditional statements in Zsh allow you to build the applications that can perform a given action based on the evaluation of a given condition.

In an oversimplification, conditionals allow the script to make a decision based on a given value.

If Statement

The most basic conditional statement is the “if” statement which allows us to execute a block of code when the condition is true.

The syntax of an “if” statement in Zsh is as follows:

if [[ condition ]]; then

# Code to execute if condition is true

fi

We start with the “if” keyword followed by the condition that we wish to evaluate. The condition must return a Boolean value to ensure that it can be evaluated.

Next, we use the “then” keyword to open the condition body where we define the logic of what the script should do if the condition is true.

Lastly, we close the condition body using the “if” keyword.

Comparison Operators

When declaring a condition in the “if” block, you are going to use the comparison operators. This allows you to perform the various types of comparisons against other values.

The supported comparison operators in Zsh include:

  • == (equal)
  • != (not equal)
  • -eq (equal)
  • -ne (not equal)
  • -lt (less than)
  • -le (less than or equal)
  • -gt (greater than)
  • -ge (greater than or equal)

If…Else

There is a more advanced version of the “if” statement that includes an “else” block. An “else” block ensures that if the specified condition is not true, another block of code is executed.

The syntax is as follows:

if [[ condition ]]; then

# Code to execute if condition is true

else

# Code to execute if condition is false

fi

Take for example the code demonstration shown below:

#!/bin/zsh

score=2500

if [[ $score -lt 1800 ]]; then

echo "Rating not registered."

else

echo "A+ Rated!"

fi

In this case, if we compare the value of the score variable whether it is less than 1800 points, the rating is not registered. Otherwise, if the score is above 1800 points, the rating is A+.

Case Statements

Next, we have the case statements. Case statements allows us to perform different actions based on the value of a variable.

The syntax of a case statement is as follows:

case $variable in

pattern1)

# Code -> pattern1

;;

pattern2)

# Code -> pattern2

;;

*)

# Default

;;

esac

Take for example the following code:

#!/bin/zsh

day="Monday"

case $day in

"Monday")

echo "It's the start of the week."

;;

"Friday"|"Saturday"|"Sunday")

echo "It's the weekend!"

;;

*)

echo "It's a regular weekday."

;;

esac

As you might notice from the given example, the code is self-explanatory by the use of case statements.

Loop Constructs

“For” Loops

The first and most common looping construct across 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:

for item in list

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 the loop to carry out.

Finally, to close the loop body, we use the “done” keyword.

Example 1:

The following example demonstrates how to use a “for” loop to iterate over a sequence of numbers from 1 to 5:

for i in {1..5}

do

echo "Iteration $i"

done

This should print the numbers from 1 to 5 which are 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:

# Declare an array

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: MySQL
Database: PostgreSQL
Database: SQLite
Database: Redis
Database: Elasticsearch

“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:

while condition

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 the following code for example that demonstrates how to use a basic “while” loop to perform a countdown:

count=5

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 will continue to run as it never becomes false. This is also known as an “infinite” loop.

“Until” Loops

We also have a loop construct which is known as an “until” loop. An “until” loop is extremely similar to a “while” loop. But unlike a “for” loop, it continues its execution as the condition is false.

It is basically an inverse of an “until” loop.

The syntax for an “until” loop is as follows:

until condition

do

# Loop body

done

Example:

The following example shows how to use an “until” loop to wait until a given task is complete:

until ps -p 5000 >/dev/null

do

sleep 1

done

echo "Process $pid has finished."

The given loop terminates the process with the specified process. It keeps sleeping for one second until the termination is complete.

Conclusion

In this tutorial, we learned about the conditional statements and loop constructs in Zsh scripting. We also explored the examples that demonstrate the usage of these constructs.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list