Linux Shell Scripting Tutorial
Introduction Tools required for shell scripting First shell script Interacting with user Operators Special characters in BASH scripting Variables in Linux BASH scripting Arrays Integer operations floating point operations String manipulation in shell scripting Parameter substitution Command Substitution Conditional statements Looping statements Passing parameters exit status of the script Functions Sourcing filesConditional statements in linux shell scripting
You can use if else statements using below syntax
if [ condition ]
then
statements…
elif [ condition ]
statements…
else
statements…
fi
Condition can be any of the value.
-eq -> Eqality operator
-ne ->Non-Equality Operator
-gt -> greater than operator
-ge -> greater than or equal operator
-lt -> less than
-le -> less than or equal to
Examples on if statement
if [ “$mypath” == “/etc” ]
then
echo “mypath variable is equal to /etc”
else
echo “mypath variable is not equal to /etc”
fi
If you want to put “then” keyword in the same line, you will have to use semicolon after if condition.
a=11
b=22
if [ “$a” -eq 11 ] && [ “$b” -eq 22 ]
then
echo “Both conditions are true”
else
echo “One or both of the conditions are true”
fi
if [ “$a” -eq 11 ] || [ “$b” -eq 23 ]
then
echo “One or Both of the conditions are true”
else
echo “Both conditions are false”
fi
When grep command finds at least one pattern in a file, it returns 0 (condition is true)
if grep -q pattern myfile
then echo “pattern found in myfile”
fi
cmp command returns 0 when 2 files are same (condition is true).
if cmp f1 f2 &> /dev/null
then
echo “File f1 and f2 are same.”
else
echo “File f1 and f2 are not same.”
fi
Conditional operator in Linux ? operator works in the same as in Java language. Syntax of ? operator is given below.
var = <condition> ? <trueValue>:<falseValue>
If the condition is true, trueValue is assigned to variable “var”. If the condition is false, falseValue is assigned to variable “var”. For example – below statement is same as the if else block that follows.
(( a = b > 3 ? 1:2 ))
if [ b -gt 3 ]
then
a=1
else
a=2
fi
Case statements
Case statements are similar to switch …case statements in C language. Here is the syntax. Note that we need to use ;; to mark the end of case block.
case “$switch” in
1) echo “Case 1” ;;
2) echo “Case 2” ;;
esac
Web development and Automation testing
solutions delivered!!