Bash if Statement Make Decisions Bash Scripts

Bash if statement can be used to make decisions based one condition true / false. I can say validating simple condition based on condition value print statement Or execute required commands. Avoid to do simple validations manually simple write bash if statement it will do it for you how.? Let’s see.

bash if statement

bash if statement

Bash if Statement Example

bash if syntax

if [ CONDITION ]; then 
      True Statement
fi  ##If closer

in shell script if statement will start with if and end with fi

## If Statement Example
## Author : Ankam Ravi Kumar

echo -e "Please enter any number:\c"
read num
if [ $num -le 9 ]; then
echo "You Entered number $num which is with in 0-9 numbers"

Let’s see what you have written in above script and its meaning

  • Line1: We are asking user to provide any number
  • Line2: Read the Value and store in variable called $num
  • Line3: Condition is if user provides value is within 0-9 numbers then it will print echo true statement.
  • -le = Less than or equal to
  • $num equal to User Provided value print true statement Or else not print any thing

Executing if statement script

administrator@Arkit-Serv:/scripts$ sh
-e Please enter any number:10

administrator@Arkit-Serv:/scripts$ sh
-e Please enter any number:8
You Entered number 8 which is with in 0-9 numbers

As per above executed script output it’s printed true statement when user provided value is with in 9 Or else nothing printed.

Other way of writing bash if statement


bash if then statement

bash if then statement

Bash if else Statement with examples

bash if else statement

bash if else statement

if [ DECISION ]; then
   execute commands

CONDITION: if provided decision is true then it will execute bash if block or else it will execute else block

## IF-ELSE Statement to check root user is logged in or not
##Author: Ravi Kumar
## WebSite:

USER=`who |grep "$1" |head -1 |awk '{ print $1 }'`
if [ $USER > /dev/null ]; then
echo "$1 has logged in"
echo "Hi $1 Welcome"
echo "$1 has not logged in"

Let me explain the bash if else statement script

  • Line 1:  USER Variable is defined and assigned who command value
  • $1 is an positional parameter (you can pass value in first position)
  • Line 2: Validate using condition if $USER variable match with provided string then if block executes


While writing bash if statement do not forgot to provide space in between value and braces “[”   “]”. Semicolon after closing of braces. It is simple write if statement in shell scripting i hope your learned it.

Download Shell Scripting Book

Related Articles

Debug Shell Script Error Easily  

Shell Script Exit Status

Variables in Shell Scripting

Thanks for your wonderful Support and Encouragement

Stay Connected with us. Learn More and Earn More


My Name is ARK. Expert in grasping any new technology, Interested in Sharing the knowledge. Learn more & Earn More

You may also like...

Leave a Reply