Special File Types   «Prev  Next»
Lesson 8 Creating Simple shell script
ObjectiveCreate Shell script to launch Appropriate interpreter for Program

Creating Simple Shell Script

Interpreters

The various shell programs, as well as languages like Perl and Tcl/Tk, are interpreted programming languages. Thus, a program written in one of these languages must be read and executed line by line by the corresponding language interpreter. UNIX can arrange to have the file containing the interpreted program automatically start the necessary interpreter.

Creating Shell script

Let us look at how you do this by creating a simple shell program. When a text file is made executable and the first line of the file is #!pathname (where pathname is replaced by an actual path), then the file may be treated like a command. The process that is actually started is the interpreter process pointed to by pathname and the file contents are passed to the interpreter as input. For example, using vi or another editor, you create a small file called trial.sh containing a sequence of shell commands, as follows:

echo "The current date and time is"
date sleep[1] 600

You could then instruct the shell to execute the commands in trial.sh by issuing the following command:
source trial.sh

The source command allows you to execute programs that have not yet been compiled. This is because source opens up the specified shell script, then executes this script according to the shell specified in the first line. For the BASH shell, for example, the line would read::
#!/bin/sh
. You can use the source command to test shell text files before you make them executable. The output of this command would be
The current date and time is
12 Apr 1999 04:17:29

The command now pauses for 600 seconds. If you wish to exit the shell script, press Ctrl-C. You would like to have the system treat this program as an executable file. The first step is to add the line
#! /bin/sh
as the first line in the file. Let us look at the remaining steps in the simulation below:
Creating Shell Script
[1]sleep: The sleep command allows you to specify a certain period of time (usually in seconds) to wait before the system executes a command. You can use this program within a shell script to execute certain commands. The syntax is sleep followed by a number that represents the number of seconds you want to wait.