Conditions

Shell conditions helps in asserting the expressions. Conditions operators can be mathematical, boolean, realtional operators or shell specific operators.

Test Construct

test command or [ expr ] is used to see if an expression is true, and if it is true it return zero(0), otherwise returns nonzero(>0) for false.

Syntax:

test expression OR [ expression ]

test or [ expr ] works with

  • Integer (Number without decimal point)
  • File types
  • Character strings

Mathematical

For Mathematics use following operator in Shell Script

Mathematical OperatorsMeaningMathematical Statementstest statement with if command[ expr ] statement with if command
-eqis equal to5 ==6if test 5 -eq 6if expr [ 5 -eq 6 ]
-neis not equal to5 != 6if test 5 -ne 6if expr [ 5 -ne 6 ]
-ltis less than5 < 6if test 5 -lt 6if expr[ 5 -lt 6 ]
-leis less than equal to5 <= 6if test 5 -le 6if expr[ 5 -le 6 ]
-gtis greater than5 > 6if test 5 -gt 6if expr [ 5 -gt 6 ]
-geis greater than equal to5 >= 6if test 5 -ge 6if expr[ 5 -ge 6 ]

Note

== is equal, != is not equal.

String

For string Comparisons use

OperatorMeaning
string1 = string2string1 is equal to string2
sting1 != string2stgring1 is NOT equal to sting2
stirng1string1 is NOT NULL or not defined
-n string1string1 is NOT NULL and does exist
-z string1string1 is NULL and does exist

File and Directory

Shell also test for file and directory type

TestMeaning
-s fileNon empty file
-f fileNon empty file
-d dirIs directory exist and not a file
-w fileIs file writable
-r fileIs read only file
-x fileIs file executable
f1 -nt f2 # file f1 is newer than f2
f1 -ot f2 # file f1 is older than f2

Logical Operators

Logical operators are used to combine two or more condition at a time

OperatorMeaning
! expressionLogical Not
expression1 -a expression2Logical AND
expression1 -o expression2Logical OR

if Condition

Syntax:

if test cond1
then
  ## statements
fi

Here the condition will be checked and if it return true then the statements inside it will be executed, otherwise it will execute the statements after the condition if any.

Example:

cat > wr1
echo –e "enter the file name:\c"
read fname
if [ -w $fname ]
then
  echo "write the data and type ctrl+d to quit"
  cat >> $fname 
fi

if…else…fi

If given condition is true then command1 is executed otherwise command2 is executed.

Syntax:

if [ condition ]
then
  # command1 if condition is true or if exit status of condition is 0(zero)
  # statements
else
  # command2 if condition is false or if exit status of condition is >0 (nonzero)
  # statements
fi

Example:

cat > ispostive
#!/bin/sh
#
# Script to see whether argument is positive
#
if test $1 -gt 0
then
echo "$1 number is positive"
fi

Run it as follows

chmod +x ispostive

ispostive 5
# output: 5 number is positive

ispostive -45
# output: Nothing is printed

ispostive
# output: ./ispostive: test: -gt: unary operator expected

The line, if test $1 -gt 0, test to see if first command line argument $1 is greater than 0. If it is true 0 then test will return 0 and output will print as 5 number is positive but for -45 argument there is no output because our condition is not true 0 (no -45 is not greater than 0) hence echo statement is skipped. And for last statement we have not supplied any argument hence error ./ispostive: test: -gt: unary operator expected is generated by shell, to avoid such error we can test whether command line argument is supplied or not by following example.

cat > isnump
# Script to see whether argument is positive or negative
if [ $# -eq 0 ]
then
  echo "$0 : You must give/supply one integers"
  exit 1
fi
if test $1 -gt 0
then
  echo "$1 number is positive"
else
  echo "$1 number is negative"
fi

Run above script as follows

chmod +x isnump

isnump_n 5
# output: 5 number is positive

isnump -45
# output: -45 number is negative

isnump
# output: ./isnump: You must give/supply one integers

isnump 0
#output : 0 number is negative

Here first we see if no command line argument is given then it print error message as ./isnump:You must give/supply one integers. if statement checks whether number of argument $# passed to script is not equal -eq to 0, if we passed any argument to script then this if statement is false and if no command line argument is given then this if statement is true.

Multilevel if-then-else

Syntax

if [ condition ]
then
  # condition is zero (true - 0)
  # statements
elif [ condition1 ]
condition1 is zero (true - 0)
  # statements
elif [ condition2 ]
  # condition2 is zero (true - 0)
  # statements
else
  # None of the above condtion,condtion1,condtion2 are true (i.e.all of the above nonzero or false)
  # statements
fi

Example:

age=39
if [ $age –lt 30 ]
then
  echo "You’re still under 30"
elif [ $age –ge 30 –a $age –le 40 ]
then
  echo "You’re in your 30s"
else
  echo "You’re 40 or over"
fi

Script to check a given string is palindrome or not

clear
echo –e "enter the string:\c"
read str1
a=`echo $str1|rev`
if [ -z "$str1" ]
then
  echo "String is null"
elif [ "$a" == "$str1" ]
then
  echo "$str1 is a palindrome"
else
  echo "$str1 is not a palindrome"
fi

Case Logic

  • The case logic structure simplifies the selection from a list of choices
  • It allows the script to perform one of many actions, depending on the value of a variable
  • Two semicolons ;; terminate the actions taken after the case matches what is being tested

Case Statement

Syntax:

case $variable in
match_1)
  # commands_to_execute_for_1
  ;;
match_2)
  # commands_to_execute_for_2
  ;;
match_3)
  # commands_to_execute_for_3
  ;;              
*) # (Optional - any other value)
  # commands_to_execute_for_no_match
  ;;
esac

The last part of the case statement

*)
  commands_to_execute_for_no_match
  ;;

is optional.

Example:

cat > car
# if no vehicle name is given
# i.e. -z $1 is defined and it is NULL
#
# if no command line arg
if [ -z $1 ]
then
rental="*** Unknown vehicle ***"
elif [ -n $1 ]
then
# otherwise make first arg as rental
rental=$1
fi
case $rental in
  "car") echo "For $rental Rs.20 per k/m";;
  "van") echo "For $rental Rs.10 per k/m";;
  "jeep") echo "For $rental Rs.5 per k/m";;
  "bicycle") echo "For $rental 20 paisa per k/m";;
  *) echo "Sorry, I can not gat a $rental for you";;
esac

#script that reconises the key that is typed
echo "Hit a key, then hit return."
read kp
case "$kp" in 
  [[:lower:]])echo "lower case key is typed";;
  [[:upper:]])echo "upper case key is typed";;
  [0-9])echo "digit is typed";;
  *)echo "special character key is typed";;
esac

#A script that wishes as per the system time
#file name is wish.sh

hour=`date +%H:%M`
case $hour in
  0?:??|1[0-1]:??)echo "Good Morning . Its $hour A.M";;
  1[2-7]:??)echo "Good Afternoon. Its $hour P.M";; 
  1[8-9]:??|2?:??)echo "Good evening. Its $hour P.M";;
esac

Give execute permission and execute as follows:

./wish.sh
Good Morning . Its 10:43 A.M

Subscribe For More Content