Main index

Introducing UNIX and Linux


Getting started

Overview
Using UNIX
      Usernames
      Logging in
Logging out
Commands
      Typing in commands
      Commands and options
Communication with other users
      Email
      Other communication facilities
Files
      The editor Vi
            Vi commands (command mode)
            Vi commands (colon mode)
      Other editors
Input and output
      Scripts
      Here-documents
      Pipes
      Making copies of input and output
      Pagers
Emergencies
Getting help
Summary
Exercises

Scripts

A method of performing several commands, one after the other, is to create a file containing those commands, one per line, and then 'execute' that file. As an example, create a file using Vi, called (say) whenandwho, and containing two lines:

date
who

Now, type sh whenandwho and the commands date and who mentioned in the file whenandwho will be executed, and you will get

sh whenandwho
Tue Dec 4 20:10:39 GMT 2001
chris    pts/1   Dec 3 07:21 (console)
sam      pts/3   Dec 3 08:38 (console)
jo       pts/4   Dec 3 14:58 (console)

A file such as whenandwho, which contains commands, is called a shell script ('script' for short).

At this stage it is important to understand how UNIX executes commands in a script. When you are logged into your system, you will be communicating with it via a program called a shell. The shell that is run from the moment you log in to the end of your session is your login shell. It is possible to run further copies of the shell by typing the command sh. In order to execute a shell script, the program sh is run, but instead of taking standard input from your terminal, the input comes from the file. Thus while the script is executing there are two copies of sh running. The login shell runs one command, namely sh, and this shell executes the commands in the file.

When writing scripts, the command echo is very useful. This command takes arguments and simply copies them to the standard output, thus:

echo Hello there
Hello there

Worked example

Write a script called niceday to display today's time and date together with a user-friendly message, thus:

sh niceday
The time and date are now:
Tue Dec 4 20:10:39 GMT 2001
Have a nice day!

Solution: We can use date to output the date and time, and echo to output the messages on lines 1 and 3. To create the file niceday, use either Vi, or if your typing is good, simply use cat:

cat >niceday
echo The time and date are now:
date
echo Have a nice day!

ctrl-D


Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck