Bash If , Else If Conditionals

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/bash-if-else-if-conditionals/
PINTEREST
PINTEREST
INSTAGRAM

Bash provides programmatic conditional statements. Conditionals provides decision point for the application flow. For example if the file exists do this if not do another thing like logic operations.

Syntax

As we see there is different type of syntax of if statements. Actually they are very similar each other in logic. We will look them in detail below.

Single Condition If

This type of if syntax is very simple we will just check single condition and then execute required code.

This is very simple example first we look if line where it is true which means condition is met so below then branch will be executed. Then branch prints “TRUE” and fi ends if branch.

Two Condition With Else

We can improve our previous if condition and add a condition if first condition it not met. Think this like true or false. For two situation there is two branch.

Multiple Condition If

Generally there will be more than one condition. We can specify multiple conditions using

multiple elif statements like below.

In this example we have three case where first is equal or greater  than 18 with the if line. Second is elif line and looks equal or greater than 7. Third one is else statement which is logically below 7.

LEARN MORE  How To Compare String In Bash Linux?

-ge is used as greater or equal operations.

[ .. ] is used to output result of the compare operation inside it to the condition.

Now we have got basic understanding of condition usage we can look examples for different situations.

Check If A File Exist

I think one of the most wanted example is to check if a file exist and execute code according the result.

Check If A Softlink Exist

We can check if provided file  is exist and symbolic link.

Compare Numbers

It can be compare two variables as number like below.

We compare two variables named $a and $b with -le with means lower or equal. If compare returns true We print the message to the console.

String Compare

String variables can be compared too. For example we may want to check current user and compare if it is root.

We get current user name with whoami command and compare if it is different from “root” with != . If the username is different than root we print message to the console.

LEARN MORE  How To Compare String In Bash Linux?

Check If A Variable Is Defined

It is very useful to check if a variable is set in the script file.

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/bash-if-else-if-conditionals/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)