Linux

Conditional statements if and else in scripting Linux

if statement

If as the name suggest is a conditional statement often used in bash scripting. If evaluates a statement if it's true then all the code inside the if's block gets executed.

So basically if condition matches then it returns true else false as simple as that.

It is really useful you can control your script's flow by making certain decisions.In shell scripting it's syntax is very different to other languages like c and cpp.

let's look at the following example.Save and execute the code and see what happen:

else statement

Ok now we know that what if is . Let's say if your condition is evaluated false then obviously it will completely ignore code inside if,in such situations we use else if your condition is false then else's block gets executed.

#!/bin/bash
num=123
if [ $num -gt 100 ]
    then 
echo "number $num is greater"

else 
echo "number is smaller"
fi

The above code would produce number 123 is greater output.We checked whether the 123 is greater than 100 or not. Since condition is true it prints the statement right after then.

Rules for creating if statements:

Comparison operators in shell scripting

Demonstrating operators with scripts:

-eq

#!/bin/bash 
echo  "enter first number"
read num1
echo "enter second number"
read num2

if [ $num1 -eq $num2 ]
 then
echo "numbers are equals"
fi 

-gt

#!/bin/bash 
echo  "enter first number"
read num1
echo "enter second number"
read num2
if [ $num1 -gt $num2 ]
 then
echo "$num1 is greater"
else
echo "$num2 is greater"
fi

In the same way you can use all the operators.


Checking file exists or not

Now with the help of if we are finally going to do something useful.We will search whether a file and directory exists or not.Follow the code below:

#!/bin/bash 
echo  "enter  a file name"
read file
 if [  -f $file ] 
then 
 echo "file exist"
else 
echo "file does not exist"
fi

-f tells shell to find file in your current directory, if it finds the will print if's block else esle's.

Search for directory/folder

Just one difference replace -f with -d.

Search for files in specific directory

If you want to search files in a specific directory then you have to give path to.

You have to supply full path like /etc/hosts try this out.File hosts exist in etc directory.

 
#!/bin/bash 
echo  "enter  a full path of file"
read file
 if [ -f $file  ] 
then 
 echo "file exist"
else 
echo "file does not exist"
fi