Blessen Cherian, CTO and Executive Team Member of bobcares.com writes, "Shell scripting is nothing but a group of commands put together and executed one after another in a sequential way. Let's start by mentioning the steps to write and execute a shell script."
Step
1: touch a file
e.g.:
touch Firstshellscript.sh
Step
2: Open the file using the command vi or pico
e.g.:
vi Firstshellscript.sh
Step
3: All shell script should begin with "#!/bin/bash ".
This line is called the Shebang and this line looks like a comment
but its not. It's a message which talks about the interpreter to be
used for this script.
Normally the format is #!
<path of the bash installation if its a bash script >
Step
4: Write the code / script which you want to develop in the file
named Firstshellscript.sh. Here let's write our first shell script
and let it be the normal hello world display script.
Step 5: For
hello world to be displayed in the shell script. Put this content in
the file Firstshellscript.sh.
echo "Hello World"
Step 6: Next
step is to make the script executable by using the command chmod
e.g.:
chmod 744 Firstshellscript.sh
or
chmod u + x
Firstshellscript.sh
Step
7: Execute the script using the command sh
i.e.
bash> sh Firstshellscript.sh
If
you want to see the entire execution then use the command
sh -xv < script name>
Step 8: The
above command would display the contents like what is shown below
bash> sh
Firstshellscript.sh
bash > Hello World
Finally
Success, we have written our first shellscript and executed it.
A hello world script will
look like what is shown below, if you cat or open the script named
Firstshellscript.sh
cat
Firstshellscript.sh
#!/bin/bash
echo Hello World
Comments in a Shell
All
lines beginning with # is a comment in shell scripting. You can have
multiple comments by using colon and single quotes.
e.g.:
:' This is a comment
line
Again this is a comment
line
My
God again this is a comment line'
Notes:
This will not work if there is a single quote in between the
contents.
Variables
As
you all know, variables are the most significant part of any software language,
be it Perl, C or anything. Similarly,
in shell scripting as well variables are very significant and is classified
mainly into 2. They are System Variables and User Defined Variables.
The
System Variables are variables which are already defined and kept in
the OS and they are also called Environment Variables. These
variables are all named in capital letters. One can see these
variables and their values by executing the command set. Examples of
System variables are PWD, HOME, USER etc. The values of these system
variables can be displayed individually by echoing the System
variables i.e. echo $HOME, will display the value stored in the
system variable HOME.
To set a System Variable
use "set" command
e.g.:
bash > set $PATH=/home/blessen/shellscript
These
kinds of variables are commonly used in scripting. They are normal
variables but their variable name should not be in capital letters,
should not start with a number etc. An ideal naming of variable will
be like _define_tempval.
To
set or define a user defined variable, please read below.
When
we assign or create a variable we just write the variable name, equal
to its value i.e. _define_tempval = blessen. Now to use / display the
value in the variable _define_tempval we have to use echo command
i.e.
echo
_define_tempval. The out put of which will be blessen
Please
find an example script which will set a variable named username and
displays its content on the screen when it is executed.
#!/bin/bash
username=blessen
echo " The
username is $username"
These
are variables which pass values or argument to a script to process
it. These variables which are passed into the script are accessed
using $1,$2...$n where $1 is the first command line argument and $2
the next etc. The delimiter is space here. $0 is the name of the
script. The variable $# will display the number of command line
argument supplied.
Let
me explain. Consider a script which will take in 2 command line
arguments and displays it. The name of the script is commandline.sh
and the script will look like the one below
#!/bin/bash
echo "The first
variable is $1"
echo "The second
variable is $2"
When
I execute commandline.sh with command line argument like blessen and
lijoe then the output of the script will be like the one shown below
bash>sh
commandline.sh blessen lijoe
The first variable is
blessen
The second variable
is lijoe
This
variable tells us if the command executed just above this was
successful or not. The variable is represented using $?. If the value
is 0, it means that the command which was executed just above this
was successful. But if the value is any other number it means that
the above command was unsuccessful. Thus it is very useful in
scripting.
For testing, create a
file named test by using the command touch test. Then try cating the
file
bash > cat test
Then
check the value of $?.
bash> echo $?
0
The value is zero because
the command was successful. Now try catting a file which is not
there. Let it be xyz1.
bash> cat xyz1
bash> echo $?
1
The
value 1 for the exit status shows that the above command was unsuccessful.
I
am sure most of the programmers have learned and most probably worked
with variables and its scope. In shell also we use the scope of a
variable for various programming activities. In shell there are 2
types of scope. One is global and other is local scope. From the name
itself you can understand that scope of global variable is throughout
the program i.e. any other shell program can use these variables for
its functioning and its set using the export command.
Syntax
is:
variable1=<its
value>
export variable1
In
shell program the local variables are defined using a local tag
before the variables, while it is defined.
Syntax is:
local variable=<some
value>
The below script will
demonstrate the scope of a local and global variable.
#!/bin/bash
function
display()
{
local local_var=100
global_var=blessen
echo " local
variable is $local_var\n";
echo "global
variable is $global_var\n";
}
echo "
======================"
display
echo "=======outside
========"
echo "local
variable outside function is $local_var\n";
echo "global
variable outside function is $global_var\n";
Input and Output in
shell scripting
For
taking inputs from keyboard we will have to use a tool provided by
shell which is called read. The read command will read the values
which are typed from keyboard and assigns it to the variable
mentioned along with it.
Syntax
is: read <variable name>
For
outputting, we use echo command and we have already dealt with it in
our above explanation.
Syntax
is: echo "statement to be displayed"
Arithmetic
Operations in shell scripting
Like
all other scripting languages shell script also allows us to play
with numerical and functions associated with it like addition,
subtraction, multiplication and division. To do these arithmetic
operations a function called expr is used, which tells the shell
script interpreter that these are numerical on which the specified
function is to be performed, i.e. expr a + b means add a and b .
Syntax:
expr <expression>
e.g.:
sum=`expr 12 + 20`
Similarly
syntax can be used for Subtraction, Division and Multiplication.
There is another way to handle Arithmetic operations; include the
variables and function inside a square bracket which starts with a
$sign. The syntax is
Syntax
is: $[expression / statement]
e.g.:
echo $[12 + 10]
Conditional Loops
Lets
have some fun with a conditional statements like "if condition “. Most
of the time, we shell programmers have situations where we have to compare two
variables and execute certain statement depending on true or false of the condition.
So in such cases, where we have to execute certain set of commands, depending
on certain conditions then we have to use if condition. The syntax of if is
show below
Syntax:
if
[Conditional statement]
then
..Any
commands/statements ..
fi
For
conditional check we can also use a different form of if condition
using the test condition. The syntax of test is test <condition>.
The new if condition will look like the one below
if test Conditional
statement
then
..Any
commands/statements ..
fi
The
below script will prompt for entering the username and if the user
name is blessen then it will display the message showing that I have
successfully logged in. If it's not blessen then it will display
the message “wrong username'.
#!/bin/bash
echo " Enter
your username:"
read username
if test
$username=blessen
then
echo "
Success!!!, you are now logged in"
else
echo
“Sorry, wrong username"
fi
Test the above for
yourself.
Variable
Comparison
In
shell script while have a different way to compare variables . If
the value of a variables to be compared are numerical then you have
to use options like
-eq For equal to
-ne Not Equal to
-lt Less than
-le Less than or
equal to
-gt Greater than
-ge Greater then or
equal to
If the value of variables to be compared are strings then you have
to use options like
= Equal too
!= Not Equal
too
> Greater than
= Greater than or equal to
< Less than
<= Less
than or equal to
Loops
In this section we will
deal with the loop statements like for and while loop.
Most
commonly used loop is for loop and in shell script there are 2 types of for
loop. One type of for loop is similar to the C programs for loop and the other
type of for loop will be new to you all.
Syntax for first type
of for loop:
for
((initialization;condition;increment/decrement))
do
....statements....
done
Syntax
for second type of for loop:
for
<variable> in <list of option >
do
....statements ....
done
The
below script will read all the contents of /etc/passwd file and
displays each line one by one.
e.g.:
#!/bin/bash
count=0
for i in `cat
/etc/passwd'
do
count=`expr $count +
1`
echo "Line
$count is being displayed"
echo $i
done
echo "End of
file"
Another
example on forloop, where we use 'seq' generator to generate the
sequence.
e.g.:
#!/bin/bash
for i in `seq 1 5`
do
echo $i
done
While
loop is another useful loop used in all programming languages. This
loop will continue executing till the condition specified is met.
Syntax
is: while [condition]
do
...statement ....
done
The below example script
is a simple script which assigns value one to the num variable and
adds one to the value of num each time it goes round the loop until
the value of num is less than 5.
e.g.:
#!/bin/bash
num=1
while
[$num -lt 5]; do
num=$[$num + 1]
echo $num
done
Select
and Case Statement
We
have learned the switch case in C programming. The combination of
select and case provides us with the same feature. Select statement
is not at all a part of case statement but I just put it together for
you to understand how both of it can be used in programming
Syntax
of Select:
select <variable>
in <list>
do
..statements...
done
Syntax of Case:
case $<variable>
in
<option1>)
statements;;
<option2>)
statements;;
*) echo "Sorry
wrong option"
esac
The example below will
explain the usage of select and case together. Example below will
display the options of service's which needs to be restarted in a
machine. When a particular option is selected then the corresponding
service will be restarted.
e.g.:
#!/bin/bash
select options in
"apache" "named" "sendmail"
do
echo
"***********************"
case $options in
apache)
/etc/rc.d/init.d/httpd restart;;
named)
/etc/rc.d/init.d/named restart;;
sendmail)/etc/rc.d/init.d/sendmail
restart;;
*) echo "Nothing
will be restarted"
esac
echo
"***********************"
break
# If this break is not
there then we wont get a shell prompt
done
Functions
In
the modern world where all programmers use OOPs model for
programming. Even we the shell programmers are also not far behind.
We too break our codes into small chunks called functions and call
them by name in the main program. This approach helps in debugging,
code re-usability etc.
Syntax for function is:
function <name of
function ()>
{# start of function
statements
} #end of function
The
function is invoked by just writing their function names in the main
program.
Please find an example
below which uses function for code re-usability.
e.g.:
#!/bin/bash
function sumcalc
{
echo "Enter the
first number:"
read num1
echo "Enter the
second number:"
read num2
sum=$[$num1 + $num2]
}
sumcalc
echo "$sum --
O/P from function sumcalc"
Debugging Shell Script
Now
and then, I have found people debugging their C program and other
programs. Hence I wish to include the option to debug shell script
for our shell programmers. We shell programmer are not far behind any
other programmers. To debug a shell program use the option -x and -v
along with sh where using -x option will expand each simple command,
for command, case command, select command, or arithmetic for command,
display the expanded value of PS4, followed by the command and its
expanded arguments or associated word list . -v option is for
verbose.
Syntax and Usage of
debug options
e.g.
sh -xv Firstshellscript.sh
Conclusion
I
believe that this article has aided all the readers to write and
debug a shell script by their own.
Mr.
Blessen Cherian
CTO and Executive Team Member
Bobcares and Poornam Info Vision Pvt Ltd
poornam.com | bobcares.com | blessen.com
Email : blessen@poornam.com
Thanks for your very straight-forward article. I would have liked a little more on the select statements and more advanced examples (which you mentioned you'll provide in your next post :). Just a quick remark: You while example doesn't work because the $ and the 5 are right next to the []. Instead, there should be spaces, as in while [ $num -lt 5 ]; do. Cheers. |