Bash Scripting: Conditionals - JohnHau/mis GitHub Wiki

A conditional in Bash scripting is made up of two things: a conditional statement and one or more conditional operators.

Bash scripts give us two options for writing conditional statements. We can either use an if statement or a case statement. In some situations, a nested if statement can also be helpful. These conditional statements only work by using operators. An operator could tell the statement to check if two numbers are equal, or if one is greater than other, etc.

The combination of conditional statements and operators is how we write Bash scripts that can proceed with a specific set of instructions depending on whether or not a condition matches our specifications. In this tutorial, you will learn how to use conditionals in Bash scripting on a Linux system.

In this tutorial you will learn:

How to use if and case conditional statements How to use conditional operators

Bash Scripting: Conditionals examples

image

image

image

Since our if statement used the -eq operator to determine if the two numbers are equal to each other, and they indeed are, the first clause was executed, thus we got “the numbers match” as output.

image

What is happening in the script? The date +"%a" command is getting information about what day of the week it is. Then our case statement will check whether the result is Mon, Tue, Wed, Thu, or Fri. If it is, then it matches pattern number 1 and will echo “today is a weekday.” If that does not match, it checks to see if the date is Sat or Sun. If it is, the script echoes “today is the weekend.” Lastly, in case there is a problem with the system and the date command returns some other kind of information, the wildcard will be matched and we will get a “date not recognized” result. image

image

The point of a nested if is that the second if statement is only used if the first if statement is true. In this case, our script only checks the time of day if it first determined that the day of the week is Mon-Fri. We have left comments in the script to make this easier to digest. Closing Thoughts In this tutorial, you saw how to use conditional statements and operators in a Bash script on Linux. Conditionals are an essential part of many Bash scripts, and give us the opportunity to adapt our scripts to a variety of situations, as certain parts can be configured to only execute when particular conditions are met.