How To Use if-else in Shell Scripts

Try this guide with our instant dedicated server for as low as 40 Euros

If Else in Shell Scripts

The if-else statement is a robust control structure in shell scripting that allows you to make decisions and run different blocks of code based on particular criteria.

During the execution, the if-else in the shell script evaluates the conditional statement and selects a block of code based on whether the statement is true or false.

Conditional programming plays a crucial role in any programming language since it allows us to execute particular statements within our program instead of executing every line by default. The if-else statement is used in shell scripts to handle this specific problem.

Table Of Content

  1. How Does if-else Work in Shell Scripts?
  2. Logical and Other Operators For if-else in a Shell Script
  3. Using if-else in Shell Script
    1. Determine if Two Values are Identical
    2. Compare Two Values
    3. Determine Whether a Number is Even
    4. Create a Simple Password Prompt
  4. Conclusion

How Does if-else Work in Shell Scripts

You need to understand how a block with an if-else statement works to see why it is vital to a shell script. We’ll first look into the structure of the conditional function to understand if-else in shell scripts.

Here’s the high-level structure of an if-else in a shell script:

if [condition]
then
statement1
else
statement2
fi

In this syntax, you can see four keywords: if, then, else, and fi.

Let’s dig a little deeper into this if-else in a shell script. 

  • The keyword if is followed by the condition.
  • This condition is evaluated to determine which statement block (1 or 2) the processor will execute. 
  • The processor executes statement block 1 if the condition evaluates to be TRUE. If not, the processor executes statement block 2. 
  • The fi is used to terminate the if-else in a shell script.

It’s vital to remember that shell scripting is case-sensitive, like most programming languages. As a result, you must exercise caution when using keywords and variable names in your shell script.

Logical and Other Operators For if-else in a Shell Script

As you can guess, the real power of the if-else structure is the conditional statement that the processor evaluates to determine which code block is executed.

You can use the following operators to add complexity and access other script elements. 

Operator Description
&& Logical AND
|| Logical OR
$0 Argument 0, i.e., the command that’s used to run the script
$1 The first argument (change number to access further arguments)
-eq Equality check
-ne Inequality check
-lt Less Than
-le Less Than or Equal
-gt Greater Than
-ge Greater Than or Equal

Using if-else in Shell Script

Now that you know the basics of if-else in shell scripts, let’s see some examples of how this structure allows you to accomplish exciting outcomes.

Determine if Two Values are Identical

Let’s start with a fundamental example – determining if two numbers are identical.

We start by initializing two variables, a and b, and then use the if-else structure to determine whether the two variables are equal.

Here’s our sample bash script:

#!/bin/bash
m=1
n=2

if [ $n -eq $m ]
then
echo "Both variables are the same"
else
echo "Both variables are different"
fi

When you execute the script, the output is:

Both variables are different.

This happens because the conditional statement was TRUE. 

Compare Two Values

A more typical application of the if-else in shell scripts is to compare two values. This is a useful operation where a variable is compared to a fixed value (constant) or another variable.

We initialized two variables in our sample bash shell script and used the if-else statement to determine which variable was greater.

#!/bin/bash
a=2
b=7
if [ $a -ge $b ]
then
echo "The variable 'a' is greater than the variable 'b'."
else
echo "The variable 'b' is greater than the variable 'a'."
fi

The output of this script would be:

The variable ‘b’ is greater than the variable ‘a’.

Determine Whether a Number is Even

Another interesting application of if-else in a shell script is to see if a variable contains an even or odd value. For this, we used the modulus operator that takes a number and divides it by a divisor, returning the remainder.

Here’s the sample bash shell script:

#!/bin/bash
n=10
if [ $((n%2))==0 ]
then
echo "The number is even."
else
echo "The number is odd."
fi

The output of the above script is:

The number is even

You’ll notice two interesting things about the above sample script:

We’ve put a portion of the condition inside double brackets. This is because the modulus operation must be completed before the condition can be checked.

Furthermore, enclosing statements in double brackets executes them in C-style, allowing you to process some C-style instructions within bash scripts.

Create a Simple Password Prompt

Let’s see a bit more complex application of the if-else in a shell script.

We’ll utilize the if-else structure to create a password prompt interface.
We will request the user’s password and save it in the variable pass.

If the user input matches the predefined password (in this case, ‘password’), the script will print “The password is correct.”

Otherwise, the shell script will report to the user that their input is incorrect and prompt for a retry.

Here’s the shell script:

#!/bin/bash
echo "Enter password"
read pass
if [ $pass="password" ]
then
echo "The password is correct."
else
echo "The password is incorrect, try again."
fi

The output of the above script is:

password prompt code using if-shell script

Conclusion

The if-else in shell script is a valuable tool for shell programmers. It is used to choose a particular code block based on how the conditional statement evaluates. The processor selects one of the available blocks based on the outcome of processing predefined conditions.

The if-else block is a critical implementation of the idea of conditional programming. This simple-looking structure makes your code more efficient and saves valuable time that the processor could spend on further processing the other parts of the script.

FAQs

Q: What is the use of “if-else” statements in shell scripts?

A: In shell scripts, “if-else” statements are used to regulate the flow of execution based on particular conditions. This structure lets you take different actions or run alternative code blocks depending on whether a condition is true or false.

Q: Can I have multiple “if-else” statements nested within each other?

A: You can nest multiple “if-else” blocks to handle more complex situations. Just make sure you use the fi keyword to close each nested block properly.

Q: Can we use an “if” statement without an “else” statement?

A: Yes, you can use the “if” statement to execute a code block when a certain condition is true without specifying any alternative action for when the condition is false.

Try this guide with our instant dedicated server for as low as 40 Euros