Unix Conditional Statements: If Then Else and Relational Operators

Conditional Statements Coding in Unix:

Shell scripts often need to be constructed to execute different instructions depending on the value of specific control variables. The different paths of execution are specified using conditional instructions.

In this tutorial, we will see about relational operators, and shell decision-making using various conditional statements. 

Unix Conditional Statements

Unix Video #15:

Unix Conditional Statements The if-elif-fi

Unix provides a number of relational operators in addition to the logical operators mentioned earlier. These can be used to compare numeric values.

  • -lt less than
  • -le less than or equal to
  • -gt greater than
  • -ge greater than or equal to
  • -eq equal to
  • -ne not equal to

Unix provides a number of ways for conditionally executing the other commands.

These are covered below:

#1) The if statements

Example:

if <control command>
 then
 <statements>
 fi

#2) The if…else statements

Example:

if <control command>
 then
 <statements>
 else
 <statements>
 fi

#3) The if…elif…else…fi statement

Example:

if <control command>
 then
 <statements>
 elif
 then
 <statements>
 else
 <statements
 fi

Given below are some example programs that illustrate these conditional statements:

#1) Check if an input number is positive:

$ echo “Enter a number”
$ read num
$ if [ $num -gt 0 ]
$ then
$ echo “It is a positive number”
$ fi

#2) Check if an input number is positive or not:

$ echo “Enter a number”
$ read num
$ if [ $num -gt 0 ]
$ then
$ echo “It is a positive number”
$ else
$ echo “It is not a positive integer”
$ fi

#3) Check if an input number is positive, zero or negative:

$ echo “Enter a number”
$ read num
$ if [ $num -gt 0 ]
$ then
$ echo “It is a positive number”
$ elif [ $num -eq 0 ]
$ then
$ echo “num is equal to zero”
$ else
$ echo “It is not a positive integer”
$ Fi

Check our upcoming tutorial to know more about Conditional Statements!!

PREV Tutorial | NEXT Tutorial