Conditional Statement in Shell Script - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Conditional Statement in Shell Script

Share This

As we are familier with conditional statements in C or other programming languages, we do understand that a set of instructions can be executed if some conditions are satisfied. Shell script also supports the conditional statements like if, if-else, nested if etc.

#!/bin/bash # Add two numbers if [ $# -ne 2 ] then echo "Usage - $0 x y" echo " Where x and y are two nos for which I will print sum" exit 1 fi echo "Sum of $1 and $2 is `expr $1 + $2`"

The following script is written to determine the biggest among the three numbers.


#!/bin/bash if [ $# -ne 3 ] then echo "$0: number1 number2 number3 are not given" >&2 exit 1 fi n1=$1 n2=$2 n3=$3 if [ $n1 -gt $n2 ] && [ $n1 -gt $n3 ] then echo "$n1 is Biggest number" elif [ $n2 -gt $n1 ] && [ $n2 -gt $n3 ] then echo "$n2 is Biggest number" elif [ $n3 -gt $n1 ] && [ $n3 -gt $n2 ] then echo "$n3 is Biggest number" elif [ $n1 -eq $n2 ] && [ $n2 -eq $n3 ] then echo "All the three numbers are equal" else echo "I can not figure out" fi

Greetings

#!/bin/bash h=`date +%H` if [ $h -lt 12 ]; then echo Good Morning elif [ $h -lt 18 ]; then echo Good Afternoon else echo Good Evening fi

Leap Year checking

echo -n "Enter year (YYYY): " read y a=`expr $y % 4` b=`expr $y % 100` c=`expr $y % 400` if [ $a -eq 0 ] && [ $b -ne 0 ] || [ $c -eq 0 ] then echo "$y is leap year" else echo "$y is not a leap year" fi

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.