Unix Tutorial 11 : Conditional Statements

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
he Shell Switch Case Syntax and Examples:
case <word> in
 <first pattern>)
 <statements>
 ;;
 <second pattern>)
 <statements>
 ;;
 *)
 <default statements>
 ;;
 esac
Here, the value of the word expression is matched against each of the choice patterns.  If a match is found then the corresponding statements are executed until the ‘;;’ statement is encountered.  If there is no match, the default statements under ‘*)’ are executed.
The following is an Example of a switch case program:
 echo “Enter a number”
 read num
 case $num in
 [0-9])
 echo “you have entered a single digit number”
 ;;
 [1-9][1-9])
 echo “you have entered a two-digit number”
 ;;
 [1-9][1-9][1-9])
 echo “you have entered a three-digit number”
 ;;
 *)
 echo “your entry does not match any of the conditions”
 ;;
 Esac

Comments

Popular posts from this blog

Hive Tutorial 31 : Analytic Functions

Hive Tutorial 37 : Performance Tuning

How to change sqoop saved job parameters