Linux Shell Scripting TutorialIntroduction 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 files
Conditional statements in linux shell scriptingYou can use if else statements using below syntax
Condition can be any of the value.
if [ condition ] then statements… elif [ condition ] statements… else statements… fi
Examples on if statement
-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
If you want to put “then” keyword in the same line, you will have to use semicolon after if condition.
if [ “$mypath” == “/etc” ] then echo “mypath variable is equal to /etc” else echo “mypath variable is not equal to /etc” fi
When grep command finds at least one pattern in a file, it returns 0 (condition is true)
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
cmp command returns 0 when 2 files are same (condition is true).
if grep -q pattern myfile then echo “pattern found in myfile” fi
Conditional operator in Linux ? operator works in the same as in Java language. Syntax of ? operator is given below.
if cmp f1 f2 &> /dev/null then echo “File f1 and f2 are same.” else echo “File f1 and f2 are not same.” fi
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.
var = <condition> ? <trueValue>:<falseValue>
(( a = b > 3 ? 1:2 )) if [ b -gt 3 ] then a=1 else a=2 fi
Case statementsCase 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