If Condition Shell Scripting

If Condition - Shell Scripting

If Condition - Shell Scripting - 5.0 out of 5 based on 1 vote
User Rating:  / 1
PoorBest 

If the condition is true then the set of action/commands will be executed else it will check for another condition if that condition is true then it will execute those set of actions else it will execute the else part

Code:

open a editor and write the below mentioned code

#!/bin/bash

a=10

if [ $a -eq 20 ];then

 echo "20"

elif [ $a -eq 10 ];then

 echo "10"

else

 echo "else"

fi

To execute:

sh if.sh

or 

bash if.sh

or

chmod 755 ./if.sh

chmod command is used to change permission of a file.

./if.sh

 

Conditional Expression:

String1 == string2 true if both are equal

String1 != string2 true if both are not equal

-lt true if number is lesser than

-le true if number is lesser than or equal to

-gt true if the  number is greater than

-ge true if the number is greater than or equal to

-eq true if the numbers are equal

-ne true if the numbers are not equal

-z string : true is the string is empty

-f file : true if the file exists

-d directory : true if the directory exists

-n string : true if the string is non zero 

code:

open a editor and write the below mentioned code

#!/bin/bash

if [ -z "$testing" ];then

 echo "String is null"

fi

if [ -n "$a" ];then

 echo "String is not null"

fi

if [ -f "logs/test.log" ];then

 echo "file exist"

fi

if [ -d "logs/" ];then

 echo "directory exist"

fi

if [ -s "a" ];then

 echo " file is not empty"

else

 echo "file is empty"

fi

 

You are here: Home Tutorials Shell Scripting If Condition