Search This Blog

2014/03/31

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;

Writing Hello World Program in Bash


Go To Terminal ,open your text editor in my case I am using Kwrite on fedora kde.
Gedit from Gnome will also work instead of Kwrite.

as
Kwrite /home/sangram/Bash/HelloWorld.sh

Now your text editor will open add Following code in it and save.


#!/bin/bash
# My first script
echo "Hello World!"


Now close your text editor.

On Terminal change your directory to directory holding your HelloWorld.sh

One can cross verify in which directory currently he is working my issuing

pwd” command.”pwd” command stand for present working directory.

To able to run our shell script just created we need to change permissions of file hence

Kwrite /home/sangram/Bash/HelloWorld.sh

Now we are ready to run our first shell script,To run your script write following command on Terminal.

bash HelloWorld.sh

Output:


[sangram@localhost Bash]$ bash HelloWorld.sh
Hello World!
[sangram@localhost Bash]$ s