Product SiteDocumentation Site

Passing command-line options to your script

The listrpmpkgs script used so far isn’t very useful. It performs one command and that’s it. We cannot customize it without writing a new script.
One way to make a script more flexible is to allow it to use command-line options. Just like the rpm command accepts a zillion options, you can make your scripts accept options.
Shells define special variables for the command-line options passed to the shell. Table 15-2 lists these options.
Table 15-2: Shell variables for command-line options
Variable
Holds
$0
The name of the script itself, from the command line
$1
The first option
$2
The second option
$3
The third option
$4
The fourth option
$5
The fifth option
$6
The sixth option
$7
The seventh option
$8
The eighth option
$9
The ninth option
$*
All command-line options
$#
Holds the number of command-line options
Note
Use $#argv in place of $# if you use the C shell to run your scripts.
You can use these variables to allow the user to pass the text to search for, instead of always searching for rpm. With this addition, your new script, renamed rpmgrep, follows in Listing 15-1:
Listing 15-1: rpmgrep
#!/bin/sh
rpm -qa | grep $*
This script now expects a command-line option that holds the text to search for. Mark this script as an executable; then you can run it as follows:
$ ./rpmgrep python
python-devel-2.2.1-17
gnome-python2-gtkhtml2-1.99.11-8
gnome-python2-canvas-1.99.11-8
gnome-python2-1.99.11-8
rpm404-python-4.0.4-8x.27
orbit-python-1.99.0-4
gnome-python2-bonobo-1.99.11-8
gnome-python2-gconf-1.99.11-8
libxslt-python-1.0.19-1
libxml2-python-2.4.23-1
python-optik-1.3-2
python-2.2.1-17
rpm-python-4.1-1.06
mod_python-3.0.0-10
python-tools-2.2.1-17
If you want to make this command available, copy it to a directory in your command path as described in the preceding section.