Datasheet
Task 1.9: Write Basic Scripts
45
Duration
This task will take about an hour to complete. Writing real-world scripts can take anywhere
from a minute or so up to several hours or even days, depending on the complexity of the script
and your own proficiency at script writing.
Setup
To perform this task, you must log into your computer as an ordinary user. One of the scripts
presented in this task requires root access to run. You’ll also need root access if you want to
copy any of these scripts to a system directory, but this isn’t necessary to complete the task.
You may use a text-mode or GUI login, although the first script launches X programs, so
you’ll need an X session to test it. The scripts themselves are executed from the command line,
but you’ll edit them in an editor, which may be a purely text-based editor (such as Vi or nano)
or a GUI editor (such as KEdit).
Caveats
As programs, scripts can contain bugs. Although the scripts presented in this task are fairly
simple and are likely to be harmless even with typos, bugs in scripts can cause infinite loops
(in which the script never terminates), excessive CPU use, accidental file deletions, and other
problems. These problems can be more serious if a buggy script is run as root, or even if a bug-
free script is used inappropriately by root. Thus, unless a script absolutely requires root
access, you should always develop and test scripts as a non-root user.
Procedure
The first thing to understand about scripts is how to create them: You use a text editor to type
commands, then modify the file permissions on the resulting file so that it’s executable. Once
you know how to perform these basic operations, you can proceed to create scripts that meet
the objectives of this task.
Beginning a Shell Script
Shell scripts are plain-text files, so you create them in text editors. A shell script begins with
a line that identifies the shell that’s used to run it, such as the following:
#!/bin/sh
The first two characters are a special code that tells the Linux kernel that this is a script and
to use the rest of the line as a pathname to the program that’s to interpret the script. Shell
scripting languages use a hash mark (#) as a comment character, so the script utility itself
ignores this line, although the kernel doesn’t. On most systems, /bin/sh is a symbolic link
that points to /bin/bash, but it could point to some other shell. Specifying the script as using
/bin/sh guarantees that any Linux system will have a shell program to run the script, but if
the script uses any features specific to a particular shell, you should specify that shell instead—
for instance, use /bin/bash or /bin/tcsh instead of /bin/sh.
83484.book Page 45 Monday, September 18, 2006 8:58 AM










