Tải bản đầy đủ (.pdf) (5 trang)

Standard Function Library

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (55.4 KB, 5 trang )

13
■ ■ ■
CHAPTER 2
Standard Function Library
A
fter writing many scripts, I realized there were several functions and routines I was
using repeatedly. Sometimes I would write the code for these duplicated functions again,
and other times I would copy and paste the code from an earlier script. But the best cod-
ing practice is to keep a file around that contains all of your already tested and working
functions. This creates a scriptwriter’s toolbox, or, in programming speak, a library. With
a library in place, many of the tools you need often are close at hand and you don’t have
to code the functions anew each time you need them. This chapter shows you how to set
up a standard function library and how to utilize the library in your scripts.
The Library File
The library itself is simply a collection of functions held in a single file. When the library is
brought into your script’s environment, you can call any of the library functions as if they
were in your original code. You could create a single library that contains all of your func-
tions or, if you have a large and varied number of them, create a set of libraries where each
one is specific to a category of coding.
Libraries are not only handy to have around; they eliminate redundant coding as well
as provide a common environment for all programmers involved to work from. Function
libraries reduce redundant code and speed up the development process, plus they can
reduce debugging and code-hardening time. If there are bugs in any of the functions, fixes
will positively impact all scripts that rely on those bits of code. Function libraries can also
level the programming field when working with many and varied system types by adding
a layer of abstraction between system differences and the programmer writing the code.
The following example library is very simple and contains only a single function. To
keep things organized, especially when files get large, you should write the functions with
good indenting form as well as comments about what the code does. Include in the library
file a header that lists all the functions and gives a brief description of each, along with
any variables that get defined. With the header you could include a list of revisions and


owners. This is especially useful when working in a team where other members may be
making changes.
14
CHAPTER 2

STANDARD FUNCTION LIBRARY
#!/bin/echo Warning: this library should be sourced!
# ostype(): Define OSTYPE variable to current operating system
ostype() {
osname=`uname -s`
# Assume we do not know what this is
OSTYPE=UNKNOWN
case $osname in
"FreeBSD") OSTYPE="FREEBSD"
;;
"SunOS") OSTYPE="SOLARIS"
;;
"Linux") OSTYPE="LINUX"
;;
esac
return 0
}
The first line of the library is an excellent method of ensuring that the library is sourced
rather than executed as a regular script. With this line, error output will be generated if
someone attempts to run the library instead of sourcing it into the environment. The out-
put would look like this:
Warning: this library should be sourced! /path_to_library
Another way to avoid execution of libraries is to make them nonexecutable.
The first function, ostype(), determines the operating system of the computer on
which the library is running. Because there are subtle differences between operating sys-

tems, knowing what OS your script is running on will help you take the differences into
account. There are, of course, many more operating systems than we are able to list here.
Some Useful Functions
The code in this section comes from a few utility functions that I find very useful. You
will probably come up with many more that are specifically geared toward the systems
you work with. Gentoo Linux provides an excellent example of a library of shell func-
tions. If you’re running this Linux distribution, you can find the library under the
filename /etc/init.d/functions.sh. Even if you’re not a Gentoo user, you should be
able to get a copy of this library and use it by performing an Internet search for Gentoo
and functions.sh, making sure that you follow the applicable usage guidelines con-
tained within the file.
The following are a few functions that I’ve found particularly useful to include in my
standard library. The first function is fairly straightforward, but it contains a cool trick.
Pass this function any number, and it will determine whether the number is even or odd.
This function was originally used in a moderately large environment where various tasks
needed to be load-balanced. We chose a simple method of splitting the environment in
CHAPTER 2

STANDARD FUNCTION LIBRARY
15
half based on the numeric value of the system name. The cool trick is the use of the sed
command to determine the last character of a string. Once the last digit is found, the func-
tion returns a true value of 1 if the digit is an even number and a false of 0 if it is not. I will
discuss this command and others like it in Chapter 24.
evenodd() {
# determine odd/even status by last digit
LAST_DIGIT=`echo $1 | sed 's/\(.*\)\(.\)$/\2/'`
case $LAST_DIGIT in
0|2|4|6|8 )
return 1

;;
*)
return 0
;;
esac
}
This second function is one I have used many times. It determines whether a remote
system is running and connected to the network. It works by pinging the specified
machine three times and sending the output to /dev/null. Success is based on the value
of $? that is returned following the ping command. If the value of $? is 0, then the machine
is alive. The usage of the ping command is encapsulated in the setupenv() function,
which I’ll present next. The switches and usage of the ping command varies among oper-
ating systems. The usage presented here will work on Linux systems. HP-UX machines
would use the command ping $NODE 3 for the same functionality.
isalive() {
NODE=$1
$PING -c 3 $NODE >/dev/null 2>&1
if [ $? -eq 0 ]
then
return 1
else
return 0
fi
}
The final function is one you’ll find useful if you need to run your scripts on multiple
hosts, some for which you don’t know the exact configuration. It sets the path to an exe-
cutable based on the operating-system type, in this case the path to ping, and stores its
value as a variable. Your scripts can then call this variable when they need to utilize the
executable without you needing to hand-code the exact path for each unique host. You
can use this function as a template for storing the location of other executables.

You can see how this script uses the ostype() function covered earlier to determine
your OS and thus the executable path.
16
CHAPTER 2

STANDARD FUNCTION LIBRARY
setupenv() {
if [ "$OSTYPE" = "" ]
then
ostype
fi
NAME=`uname -n`
case $OSTYPE in
"LINUX" )
PING=/usr/sbin/ping
;;
"FREEBSD" )
PING=/sbin/ping
;;
"SOLARIS" )
PING=/usr/sbin/ping
;;
*)
;;
esac
}
Using Your Library
Once you’ve included a library in your shell scripting environment, all functions it con-
tains become available to your scripts. There are several ways to incorporate the library
into the environment.

You can make the library available by entering the source command at the shell
prompt, as shown here. This command evaluates the commands in a file, which in the
case of our library places its resources inside the current shell environment.
source std_lib
Another way of sourcing a library file is with dot syntax. This is a shorthand way of per-
forming the same task as the source command by replacing the command with a dot (.).
This is a built-in function included in both ksh and bash.
. std_lib
If you work with a large number of networked systems, keeping a copy of your library
on every machine promotes consistency. It is very important to be able to count on the
environment you are working in to be the same on all machines. An excellent method for
this is to store your libraries on a central NFS server to which all machines in the environ-
ment have access. This also lets you make library changes in one place that will update the
whole environment. A somewhat less desirable method would be to keep the source cop-
ies of your libraries in one place for editing and propagate any changes to the remote
machines through some utility, such as rsync. The worse case would be to manually copy
CHAPTER 2

STANDARD FUNCTION LIBRARY
17
the libraries to each machine when changes are made. This is viable only if you have an
environment with only a few systems.
If you have a heterogeneous environment, you will always have to cope with minor dif-
ferences from OS to OS or even between different versions of the same OS. A standard
library is a good way of dealing with those differences and keeping your scripts portable.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×