Bash if Conditional Statement – Syntax – Examples

Bash if

Bash If statement is used for conditional branching in the sequential flow of execution of statements.

Syntax of Bash If

Bash If statement syntax is

Note : Observe the mandatory spaces required, in the first line, marked using arrows. Also the semicolon at the end of first line. And if conditional statement ends with  fi

For including multiple conditions with AND or OR operators

For compound expressions, following if syntax is allowed.

 

Bash If : Example-1

Note : In bash, respect each token/literal. Observe the spaces provided after   if   [  string literal  "hello" and  ==

When you run the above bash if example script file in a shell program like Terminal, the result would be

 

Bash If : Compare Numbers : Example-2

This example demonstrates on how to compare numbers

When you run the above bash script file in shell program like Terminal, the result would be

 

If Expression is Condition AND Condition : Example-3

In this example, we shall learn to use AND operator to include multiple conditions in the expression.

 

If expression is Condition OR Condition : Example-4

In this example, we shall learn to use OR operator to include multiple conditions in the expression.

 

Bash If with Multiple Conditions : Example-5

In this example, we shall learn to include multiple conditions in the expression.

 

Concluding Bash If :

In this Bash Scripting Tutorial, we have learnt conditional branching in the sequential flow of execution of statements with bash if statement and example shell scripts.