Saturday, 12 November 2011

SHELL SCRIPTING

Shell Scripting

This chapter introduces you to the concept of computer programming. So far, you have entered commands one at a time. Computer programming is merely the idea of getting a number of commands to be executed, that in combination do some unique powerful function.

Introduction

To execute a number of commands in sequence, create a file with a .sh extension, into which you will enter your commands. The .sh extension is not strictly necessary but serves as a reminder that the file contains special text called a shell script. From now on, the word script will be used to describe any sequence of commands placed in a text file. Now do a

chmod 0755 myfile.sh

which allows the file to be run in the explained way.

Edit the file using your favorite text editor. The first line should be as follows with no whitespace. [Whitespace are tabs and spaces, and in some contexts, newline (end of line) characters.]

#!/bin/sh

The line dictates that the following program is a shell script, meaning that it accepts the same sort of commands that you have normally been typing at the prompt. Now enter a number of commands that you would like to be executed. You can start with

echo "Hi there"
echo "what is your name? (Type your name here and press Enter)"
read NM
echo "Hello $NM"

Now, exit from your editor and type ./myfile.sh. This will execute [Cause the computer to read and act on your list of commands, also called running the program. ] the file. Note that typing ./myfile.sh is no different from typing any other command at the shell prompt. Your file myfile.sh has in fact become a new UNIX command all of its own.

Note what the read command is doing. It creates a pigeonhole called NM, and then inserts text read from the keyboard into that pigeonhole. Thereafter, whenever the shell encounters NM, its contents are written out instead of the letters NM (provided you write a $ in front of it). We say that NM is a variable because its contents can vary.

You can use shell scripts like a calculator. Try

5
echo "I will work out X*Y"
echo "Enter X"
read X
echo "Enter Y"
read Y
echo "X*Y = $X*$Y = $[X*Y]"

The [ and ] mean that everything between must be evaluated [Substituted, worked out, or reduced to some simplified form. ] as a

No comments:

Post a Comment