Showing posts with label Shell Scripting. Show all posts
Showing posts with label Shell Scripting. Show all posts

Wednesday, February 17, 2010

Shell Scripting Continued...

Hi Folks

Along with my previous commitment about posting further more on Shell Scripting and on request from few about same, here I am again with few more details on it.

In this blog, I would try to answer basic Why, How and Where about Shell Scripting.

I received ample of comments with basic yet very valid question that

Why Should I need to write Shell Scripts ?

Here are some usage I have tried to quote :

1. Operating Systems likes Linux and other Unix-like needs automated tasks. Shell scripts are extremely useful for achieving this.
2. Shell scripts are also employed extensively in the default installations of Unix-like operating systems.
3. In daily life, programmers might need to execute series of commands most often. Executing those several commands manually at a command line interface, Shell scripts allow it to be executed automatically. And that too without having to wait for a user to trigger each stage of the sequence.

For example, in a directory with three C source code files, rather than manually running the four commands required to build the final program from them, one could instead create a C shell script, and keeping in the directory with them, which would compile them automatically.

These types of programs are also called as Batch jobs.

4. A shell script can be used to provide a sequencing and decision-making linkage around existing programs, and for moderately-sized scripts the absence of a compilation step is an advantage.
5. Shell scripts can also be useful at a need where scripts requires executed :
  1. Interactively
  2. Once, at a future date and time
  3. Repeatedly on a fixed schedule
  4. Using an HTML form

Next, I would like to shed light on How to create shell Script ?

What all I would like to mention here to answer this question is that all that is necessary to create this script is to open a plain text editor (but not a word processor), such as vim, emacs, gedit, dtpad et cetera are all valid, any text editor will do. And type the series of commands to execute them. Thats it !! Its that simple !! For adding commands to be executed, you can refer my previous post on same topic. It would help you understand the syntaxes, variables, arithmatics to be used etc. in script.

Consider a very basic example of printing Date of the System :

Filename : myDate.sh

#!/bin/bash
set `date`
echo $1 $2 $3 $6

Alternatively, the above code could be copied from this page and pasted to a blank page opened by the text editor page using the standard keyboard or mouse copy and paste functions.

After saving this plain text file, with a file name such as date (or anything else desired), the script is complete and almost ready to run. Scripts are typically run by typing a dot, a forward slash and the file name (with no spaces in between) and then pressing the ENTER key. You would come to know further ways to execute the script from command prompt down below.

Thus, for example, if the above script were saved with the name morning, an attempt could be made to execute it by issuing the following command:

./myDate

Script will print the output as : sat Aug 5 2006

However, the script probably will not run, in which case an error message will appear on the screen such as bash: ./myDate: Permission denied.

This is because the permissions for the file first have to be set to executable. (By default, the permissions for new files are set to read and write only.) The problem can easily be solved by using the chmod command with its 755 option (which will allow the file creator to read, write and execute the file) while in the same directory as that in which the file is located as follows:

chmod 755 morning

Now the script is totally ready to run..


Finally Where would I execute the Script ? is the question remained..

Command Prompt !! This is what all I can answer to this. Ha ha. Yes, serious I am. Consider you have named your script as foo. (Well, I dont know why foo. :) Its just like that !! LOL ). So once you are done writing your script, you would simply go to the command prompt and type any of following command to execute your script..
  • $ bash foo
  • $ sh foo
  • $ ./foo


Finally, I would like to share one Shell Scripting example with Menu Program ::

fnMainMenu()
{
clear
echo "======= Menu ==========="
echo "Menu :"
echo " (1) Addition"
echo " (2) Quit this Menu"
echo "Enter your option : "
read response
case $response in
1) echo "Enter First Number : "
read num1
echo "Enter Second Number : "
read num2
sum=`expr $num1 + $num2`
echo "Addition : $sum "
;;
2) exit
;;
*) echo "I dont know what you are trying?"
sleep 2
;;
esac
}
#===== Start =====
#!/bin/sh
fnMainMenu


Try this program !!

Hope I have been successful in explaining the more basics about the Shell Script and was able to answer most of your doubts on this, so feel free to share your views on this.

Friday, March 6, 2009

Introduction to Unix Shell Scripting

I would like to discuss Shell Scripting in Unix in this topic today. What I would be discussing with you is introduction to Shell Scripting, its features, command line parameters, arithmetic operations, control structures and functions usage in Shell Scripting.

Lets start with the definitions. Shell is a program provided by Unix, typically to provide interface to the Unix system. Thus, in other words, Shell is some tool for interacting user with system. Generally its either text based and command line oriented. Command Interpreter which is series of commands and takes commands from user and executes them. There are different types of Shell e..g Bourne Shell (/bin/sh), C Shell (/bin/csh), TC Shell (/bin/tcsh), Korn Shell (/bin/ksh), Bash (Bourne Again shell) (/bin/ksh) etc.

Why do we need Shell Programs ? Nice question you have... Lets concentrate now on this basic question which is generally asked. We generally may need to run tasks that are customized for different system or Some times we need to write some jobs that run on a system and we need to control those jobs we may need Shell Scripting in such and situations like those.

1.Script starts with line #!/bin/sh
2.'#' is used for commenting in script. Comments used in script always makes your code readable
3.It gives identification of author of script and date & time of update.
4.Easy to read and understand
5.Major complex sections of codes can be explained
6.Last but not least Versioning is tracked through this

These are few of features that we can generally think of it.

Lets see now what are the parameters and its usage through command line.

$0 tells you the name of script. $1, $2, $3 … tells you the 1st , 2nd , 3rd and so on parameter passed through the command line. And $# gives you no. of arguments passed to the script. If your script needs to read the input given by user through command prompt, use “read” statement .
e.g. echo “Please enter your name : ”
read name
where name would be the variable holding the user inputted value.

How arithmetic operations are carried out in Scripting is still a question. Let me explain you through the example.
e.g. i=2
j=3
k=`expr $j - $i`
echo “Result of $j - $i is : $k ”
Note here, expr is used to execute the operation and it would assign the result to the variable on left side.

Just like other programming languages, Shell Scripting also provide couple of control structures for your help. Significance of control structures is well knows world wide.. :)
If – then, For loop, While loop, Case statement are couple of control structures provided by Shell Scripting.

Lets see Syntaxes one by one for all Control Structures :
1.If- then
Syntax:
if condition then
condition is satisfied and is true
execute this block
else
if condition is not satisfied then execute this block upto fi.
fi

Here, note that condition is zero means its true and satisfied. And you can go in nested
if -else – fi .

2.For Loop
Syntax:
for { variable name } in { list }
do
execute and repeat all the statements in this block once for each item till
the list is finished
done

3.While Loop
Syntax:
while [ condition ]
do
command1
command2
command3
..
....
done
Here, Loop is executed as long as given condition is true. You need to make sure, at some point condition should get false within the loop or else it would go on executing indefinitely causing script hang.

4.Case Statement
The case statement is good alternative to Multilevel if-then-else-fi statement. It enable you to match several values against one variable. Its easier to read and write.
Syntax:
case $varName in
pattern1) command1
command2
…..
commandn;;
pattern2) command1
command2
…..
commandn;;
.
.
.
.
patternN) command1
command2
…..
commandn;;
*) command;;
esac

The $varName is compared with patterns till a match is found. And similar to case statements in
other programming languages such as PHP, shell executes all the statements up to the two semicolons as a delimiter.. *) is the default case and executed when no pattern is matched.

Hope at this point of line, you have been very much comfortable with Shell Scripting and its basics. Finally lets see how user defined functions work in Shell Scripting.

In Shell Scripting Function can be defined as a series of commands. They performs specific work to do or simply say task. Below mentioned syntax can help you understand the function in detail.
Syntax:
function_name ( )
{
command1
command2
.
.
.
.
commandN
return
}
Here, function_name is the name of function that you define, and it executes series of commands either up to return statement or end curly brace of function (whichever encounters first ) which terminates the function and passes control back to the calling point
e.g.

Type fnGetName() at $ prompt as follows
fnGetName()
{
echo “in function”
}
Call to the above function can be given with simply name of fucntion.
e.g. fnGetName

fuew !! Tired so far reading ?? ha ha .. we are not done yet but for now.. yes..!! This is enough for you to get basic idea of what is Shell Scripting. We still have tons of other areas in Shell Scripting to cover which is vast in size and will need separate site to explain and discuss it. Lets discuss it further later at some point, in mean while you can always get in touch with me for your queries through this blog and will be happy to resolve them.

Till then aloha !!