Search This Blog

Monday, March 31, 2014

Bash - working with If statement:


In bash if statement starts with 'if' and ends with 'fi'.syntax look like below

if [Boolean condition];then
statement(s) to be executed on if condition evaluate to be true
else
statement(s) to be executed on if condition evaluate to be false
fi;


look into below code spinet,it has three section

1) this section shows only if statement without no else couterpart
2) second section contain if with else
3)in third we are declaring two variables T1 & T2 and initializing it with some values.

T1="i";
T2="we";

this

The if condition is based on values of created variable bash $ stand for value of something so when we say

echo "$T1";

first the value of T1 variable is found then echoed please note that wrt $ following statement are not same

echo "$T1";#this will print value of variable T1
                          vs
echo $"T1";#this will always print T1

anything return after # on that line is considered as comment
e,g.

#this is a comment

"echo -e" appears in below code as we have newline character that need to be interpretation.

for more details on various style of "echo" construct, run command "man echo"




[CODE]

#!/bin/bash

#simple if without else
if [ 1 = 1 ]; then
echo -e "\n1) Simple IF :1=1 is a universal truth evaluate to be true once & for all\n";
fi;

#simple if with else
if [ 1 = 1 ]; then
echo -e "2) Simple IF & ELSE : 1=1 is a universal truth evaluate to be true once for all\n";
else
echo -e "2) Simple IF & ELSE :unfortunately this line will never ever execute\n";
fi;

#variable declaration & if
T1="is";
T2="we";
echo "$T1";


if [ "$T1" = "$T2" ]; then
echo -e "3) my i is my we\n";
else
echo -e "4) my i is not my we\n";
fi;

No comments:

Post a Comment