|
COPYRIGHT 2005 VNU Business Media Europe
Byline: Barry Shilliday.
Last month we introduced the Unix shell. We looked at its purpose, how to run commands and pass simple arguments or options, and we looked at environment variables. This month we will take this further and look at some simple shell scripting.
A shell script is a program that runs inside the shell. It is not as versatile as a generic programming language such as C, but it provides all the basic necessities. While other programming languages are concerned with allowing you to create utilities and applications, a shell script is designed to allow you to control the way other programs or utilities are run. In its simplest form, it is a series of programs to run and, like a simple program, is executed from top to bottom. When the end of the script is reached, the shell script ends.
So here's our basic shell script. Run an editor (such as vim or kate) and create a file called test.sh containing the following:
echo "Hello World"
echo "This is today's date:"
date
To run the script, just execute a shell with the filename as an argument:
$ bash test.sh
This command launches a new shell, which then goes ahead and executes the commands inside the file. If you remember from last month, the echo command simply returns whatever it's given, so in a script it acts like a print command. The date command returns the current date and time. In this instance, there is no difference between running each of these commands at the command line and executing them together in a script. In fact, there is very little real difference between shell scripts and interactive shell sessions in general; the shell constructs work interactively too, as we will see later.
Of course, shell scripts wouldn't be very useful at all if they were limited to running sequential commands alone. Before going any further, we should clean up the script above to use a more standard form. As it stands, the script is just a text file. It's not a good idea to have scripts like this, as there's no way of knowing how to run the script, which shell to use (see box) or, indeed, if it really is a shell script.
Unix systems use a 'magic number' to identify files. The first few bytes of...
Read the full article for free courtesy of your local library.
|