Datasheet
48
Phase 1
Working on the Command Line
Variables that are passed to the script are frequently called parameters. They’re represented
by a dollar sign ($) followed by a number from 0 up—$0 stands for the name of the script, $1
is the first parameter to the script, $2 is the second parameter, and so on. To understand how
this might be useful, consider the task of adding a user. As described earlier, in Task 1.6, cre-
ating an account for a new user typically involves running at least two commands—useradd
and passwd. You might also need to run additional site-specific commands, such as com-
mands that create unusual user-owned directories aside from the user’s home directory.
As an example of how a script with a parameter variable can help in such situations, con-
sider Listing 1.3. This script creates an account and changes the account’s password (you’ll be
prompted to enter the password when you run the script). It creates a directory in the /shared
directory tree corresponding to the account, and it sets a symbolic link to that directory from
the new user’s home directory. It also adjusts ownership and permissions in a way that may
be useful, depending on your system’s ownership and permissions policies.
Listing 1.3: A Script That Reduces Account-Creation Tedium
#!/bin/sh
useradd -m $1
passwd $1
mkdir -p /shared/$1
chown $1.users /shared/$1
chmod 775 /shared/$1
ln -s /shared/$1 /home/$1/shared
chown $1.users /home/$1/shared
When you use Listing 1.3, you need type only three things: the script name with the desired
username and the password (twice). For instance, if the script is called mkuser, you might use
it like this:
# mkuser sjones
Changing password for user sjones
New password:
Retype new password:
passwd: all authentication tokens updated successfully
Most of the scripts’ programs operate silently unless they encounter problems, so the inter-
action (including typing the passwords, which don’t echo to the screen) is a result of just the
passwd command. In effect, Listing 1.3’s script replaces seven lines of commands with one.
Every one of those lines uses the username, so by using this script, you also reduce the chance
of an error.
Another type of variable is assigned within scripts themselves—for instance, they can be set
from the output of a command. These variables are also identified by leading dollar signs, but
they’re typically given names that at least begin with a letter, such as $Addr or $Name. These
variables are the same as variables you can set at the command line (as described earlier, in
Task 1.8), but unless you use the export command, they don’t become environment variables.
83484.book Page 48 Monday, September 18, 2006 8:58 AM










