If then else structure

if-then-else-if

if condition is used for decision making in shell script.

If given condition is true then command1 is executed as shown below.


Syntax:

if condition

then

command1 if condition is true or if exit status

of condition is 0 (zero)

...

...

else

commands…

fi

 

Example:

#!/bin/bash

#FileSearch.sh

# Search a file in Current Directory

# Syntax: file -f [file_name]--->search the name of file

if test -f file_name

then

echo 'file is an ordinary file'

else

echo 'file is not a file'

fi

exit 0

 

 

Comparison operators (binary)

 

integer comparison

−eq

is equal to

if [ "$a" −eq "$b" ]

−ne

is not equal to

if [ "$a" −ne "$b" ]

−gt

is greater than

if [ "$a" −gt "$b" ]

−ge

is greater than or equal to

if [ "$a" −ge "$b" ]

−lt

is less than

if [ "$a" −lt "$b" ]

−le

is less than or equal to

if [ "$a" −le "$b" ]

#!/bin/bash

#integers.sh

# Arthemetic Operation on Integers

clear

a=1

b=2

echo$a

echo$b

#if we have to compare integers then we use the following syntax:

if [ "$a" -lt "$b" ]

then

echo "b is greater"

else

echo "a is greater"

fi

exit 0

 

string comparison

=

is equal to

if [ "$a" = "$b" ]

==

is equal to

if [ "$a" == "$b" ]

!=

is not equal to

if [ "$a" != "$b" ]

This operator uses pattern matching within a [[ ... ]] construct.

<

is less than, in ASCII alphabetical order

if [[ "$a" < "$b" ]]

if [ "$a" \< "$b" ]

Note that the "<" needs to be escaped within a [ ] construct.

>

is greater than, in ASCII alphabetical order

if [[ "$a" > "$b" ]]

if [ "$a" \> "$b" ]

Note that the ">" needs to be escaped within a [ ] construct.

−z

string is "null", that is, has zero length

−n

string is not "null".

The −n test absolutely requires that the string be quoted within the test brackets.

#!/bin/bash

#TESTING IF A STRING IS NULL or NOT

# Using if [ ... ]

# If a string has not been initialized, it has no defined value.

# This state is called "null" (not the same as zero).

if [ −n $string1 ]

then

echo "String \"string1\" is not null."

else

echo "String \"string1\" is null."

fi

# Wrong result.

# Shows $string1 as not null, although it was not initialized