If syntax linux bash

Bash If Statement – Linux Shell If-Else Syntax Example

Zaira Hira

Zaira Hira

Bash If Statement – Linux Shell If-Else Syntax Example

When coding, you might need to make decisions based on certain conditions. Conditions are expressions that evaluate to a boolean expression ( true or false ).

Statements that help to execute different code branches based on certain conditions are known as conditional statements.

if. else is one of the most commonly used conditional statements. Like other programming languages, Bash scripting also supports if. else statements. And we will study that in detail in this blog post.

Syntax of if Statements

You can use if statements in a variety of ways. The generic structure of if statements is as follows:

  • Using an if statement only: if. then. fi
  • Using and if with an else statement: if. then. else. fi statements
  • Using multiple else statements with if : if..elif..else..fi

How to Use the if Statement

When you are using a single if statement, the syntax is as follows:

if [ condition ] then statement fi

Let’s go through an example where we are comparing two numbers to find if the first number is the smaller one.

#! /bin/sh a=5 b=30 if [ $a -lt $b ] then echo "a is less than b" fi

If you run the above snippet, the condition if [ $a -lt $b ] evaluates to True , and the statement inside the if statement executes

How to Use the if .. else Statement

When you are using an if statement and you want to add another condition, the syntax is as follows:

if [ condition ] then statement else do this by default fi

Let’s see an example where we want to find if the first number is greater or smaller than the second one. Here, if [ $a -lt $b ] evaluates to false, which causes the else part of the code to run.

#! /bin/sh a=99 b=45 if [ $a -lt $b ] then echo "a is less than b" else echo "a is greater than b" fi

How to Use if..elif..else Statements

Let’s say you want to add further conditions and comparisons to make the code dynamic. In this case, the syntax would look like this:

if [ condition ] then statement elif [ condition ] then statement else do this by default fi

To create meaningful comparisons, we can use AND -a and OR -o as well.

In this example, we will determine the type of triangle using these conditions:

  • Scalene : A triangle where every side is different in length.
  • Isosceles : A triangle where 2 sides are equal.
  • Equilateral : A triangle where all sides are equal.
read a read b read c if [ $a == $b -a $b == $c -a $a == $c ] then echo EQUILATERAL elif [ $a == $b -o $b == $c -o $a == $c ] then echo ISOSCELES else echo SCALENE fi

In the example above, the script would ask the user to enter the three sides of the triangle. Next, it would compare the sides and decide the triangle type.

Читайте также:  Linux zorin os lite

Conclusion

You can easily branch your code based on conditions like if..else and make the code more dynamic. In this tutorial, you learned the syntax of if. else along with some examples.

I hope you found this tutorial helpful.

What’s your favorite thing you learned from this tutorial? Let me know on Twitter!

You can read my other posts here.

Источник

Bash: If, Else If, Else Examples

In this Linux Hint tutorial we will teach Bash scripting conditionals using IF, ELIF and ELSE commands. The IF condition is the most basic way to take conditional action in a bash scripts so its important to have a firm grasp on its syntax and options to be productive. When using IF conditions in Bash, you can optionally introduce ELIF conditions that will provide different actions depending on which of a group of conditions is TRUE. Additionally the ELSE condition can be optionally included, which will provide code to execute if none of the conditions in the group is met.

Specific Examples Shown in this Article Include:

General Syntax of Bash IF ELIF ELSE

Below is the general syntax of IF ELIF and ELSE in bash:

if CONDITION-TO-TEST; then
CODE-TO-EXECUTE- 1
elif NEXT-CONDITION-TO-TEST; then
CODE-TO-EXECUTE- 2
elif NEXT-CONDITION-TO-TEST; then
CODE-TO-EXECUTE- 2
else
CODE-TO-EXECUTE- 2
fi

Note: In the above general syntax that you can include zero, one or multiple ELIF conditions in the code block and the ELSE condition is optional.

Construction of the actual conditions has many options because the syntax of bash has so many different features and options, but a very basic template for your bash scripts would be to use the [[ double brack syntax as shown in the general syntax example and specific examples below.

if [ [ CONDITION-TO-TEST ] ] ; then
CODE-TO-EXECUTE- 1
elif [ [ NEXT-CONDITION-TO-TEST ] ] ; then
CODE-TO-EXECUTE- 2
elif [ [ NEXT-CONDITION-TO-TEST ] ] ; then
CODE-TO-EXECUTE- 2
else
CODE-TO-EXECUTE- 2
fi

Note also: That depending on your code formatting aesthetics you may like the then on the same line of the conditions or you may opt to put it in the next line as shown below:

if [ [ CONDITION-TO-TEST ] ]
then
CODE-TO-EXECUTE- 1
elif [ [ NEXT-CONDITION-TO-TEST ] ]
then
CODE-TO-EXECUTE- 2
elif [ [ NEXT-CONDITION-TO-TEST ] ]
then
CODE-TO-EXECUTE- 2
else
CODE-TO-EXECUTE- 2
fi

Now lets show specific examples of the basic variations of the IF ELIF and ELSE conditions in working examples below.

Example 1: If statement in bash on string equality

#!/bin/bash
read -p «Enter a match word: » USER_INPUT
if [ [ $USER_INPUT == «hello» ] ] ; then
echo «Hello to you as well»
fi

In this example above we use the basic IF condition with a single test of string equality and then print some output in case the condition is true based on input from the user. Note, you can place the THEN statement on the next line if you prefer that style. See the example output below:

Читайте также:  Мониторинг температуры сервера linux

linuxhint @ :~$ bash t1.sh
Enter a match word: hello
Hello to you as well
linuxhint @ :~$ bash t1.sh
Enter a match word: bye
linuxhint @ :~$

Example 2: If statement in bash on number equality

#!/bin/bash
read -p «Enter a number: » USER_INPUT
if [ [ $USER_INPUT -eq 7 ] ] ; then
echo «7 is a lucky number»
fi

In this example above, again we do a simple IF condition but in this case we demonstrate how to do a test comparison on numeric values. You can see the output below with both the matching and non matching conditions:

linuxhint @ :~$ bash t2.sh
Enter a number: 7
7 is a lucky number
linuxhint @ :~$ bash t2.sh
Enter a number: 8
linuxhint @ :~$

Example 3: If statement in bash on less than a number

In addition to -eq for equality you can also try -lt -le -gt -ge test conditions for less than, less than or equal, greater than or greater then or equal respectively. Below is a similar example with less then operator -lt:

#!/bin/bash
read -p «Enter a number: » USER_INPUT
if [ [ $USER_INPUT -lt 100 ] ] ; then
echo «Your entry is less than one hundred»
fi

Output for this script will be able to test if the input is less than 100 and run specific code on that condition:

linuxhint @ :~$ bash t3.sh
Enter a number: 99
Your entry is less than one hundred
linuxhint @ :~$ bash t3.sh
Enter a number: 101
linuxhint @ :~$

Example 4: If statement in bash with logical AND operator

This example will show how to combine multiple conditions with a logical AND condition. You can also use logical OR conditions in your IF statement constructs. Logical AND in bash code is written with double ampersand &&. Below is an example of logical AND in a bash IF condition:

#!/bin/bash
read -p «Enter a number: » USER_INPUT
if [ [ $USER_INPUT -gt 9 && $USER_INPUT -lt 100 ] ] ; then
echo «Your entry is two digits»
fi

We will test this with various outputs to prove that only if both the first and the second condition are true the output will be printed:

linuxhint @ :~$ bash t4.sh
Enter a number: 22
Your entry is two digits
linuxhint @ :~$ bash t4.sh
Enter a number: 8
linuxhint @ :~$ bash t4.sh
Enter a number: 100
linuxhint @ :~$ bash t4.sh
Enter a number: 99
Your entry is two digits

Example 5: If statement in bash with logical OR operator

Logical OR in bash scripts is written with double vertical bars ||. Let’s try the previous example again with a slight variation to test out an example of the logical OR operator:

#!/bin/bash
read -p «Enter a number: » USER_INPUT
if [ [ $USER_INPUT -lt 10 || $USER_INPUT -ge 100 ] ] ; then
echo «Your entry is NOT two digits»
fi

In this example the logical OR operator combines two conditions and only one of them or both can be true for the condition to be overall true and the code to execute. We also demonstrate the -ge operator for greater or equal numeric comparison in the above example. The script is working as expected in the output below:

Читайте также:  Arch linux deb или rpm

linuxhint @ :~$ bash t5.sh
Enter a number: 3
Your entry is NOT two digits
linuxhint @ :~$ bash t5.sh
Enter a number: 10
linuxhint @ :~$ bash t5.sh
Enter a number: 99
linuxhint @ :~$ bash t5.sh
Enter a number: 100
Your entry is NOT two digits
linuxhint @ :~$ bash t5.sh
Enter a number: 101
Your entry is NOT two digits

Example 6: elif condition in bash

We will now provide an example for multiple if conditions in the code block with ELIF. You can have zero, one, or multipe ELIF conditions in a code block. For this example we will provide two ELIF conditions as a demonstration, but you can use any number of ELIF blocks in practice.

#!/bin/bash
read -p «Enter a number: » USER_INPUT
if [ [ $USER_INPUT -lt 0 ] ] ; then
echo «Not a valid positive number input»
elif [ [ $USER_INPUT -gt 0 && $USER_INPUT -lt 10 ] ] ; then
echo «Valid 1 digit number entered»
elif [ [ $USER_INPUT -gt 9 && $USER_INPUT -lt 100 ] ] ; then
echo «Valid 2 digit number entered»
fi

We will test this code with a variety of numbers to demonstrate which if or ELIF condition is triggered:

linuxhint @ :~$ bash t6.sh
Enter a number: -1
Not a valid positive number input
linuxhint @ :~$ bash t6.sh
Enter a number: 1
Valid 1 digit number entered
linuxhint @ :~$ bash t6.sh
Enter a number: 14
Valid 2 digit number entered
linuxhint @ :~$ bash t6.sh
Enter a number: 101
linuxhint @ :~$

Example 7: If Else Statement in Bash Scripting

We will now demonstrate the ELSE condition. The ELSE condition is used in the case where the IF condition or all the ELIF conditions do not exist then the ELSE condition will be used and the code in the ELSE condition will be executed. Let’s add an example of ELSE condition to the previous example but to be clear ELIF is not required to leverage the ELSE condition. The ELSE condition can be used with a IF condition and no ELIF condition.

#!/bin/bash
read -p «Enter a number: » USER_INPUT
if [ [ $USER_INPUT -lt 0 ] ] ; then
echo «Not a valid positive number input»
elif [ [ $USER_INPUT -gt 0 && $USER_INPUT -lt 10 ] ] ; then
echo «Valid 1 digit number entered»
elif [ [ $USER_INPUT -gt 9 && $USER_INPUT -lt 100 ] ] ; then
echo «Valid 2 digit number entered»
else
echo «A valid 2 digit number was not entered»
fi

Let’s test the example code with a simple test case that should fall into the ELSE condition:

linuxhint @ :~$ bash t7.sh
Enter a number: 199
A valid 2 digit number was not entered
linuxhint @ :~$

CONCLUSION

We have seen how to use IF, ELIF and ELSE conditions to form conditional execution in many combinations in bash scripts and bash programs. For next steps you can study test conditions and the variations and varieties available for testing a condition. You can also consider the bash case statement as an alternate for conditional logic in bash scripts. Finally the GNU Bash Reference Manual is a good source of truth when looking for exact syntax details.

About the author

Linux Wolfman

Linux Wolfman is interested in Operating Systems, File Systems, Databases and Analytics and always watching for new technologies and trends. Reach me by tweeting to @linuxhint and ask for the Wolfman.

Источник

Оцените статью
Adblock
detector