Previous | Table of Contents | Next |
Adapting getPID for BSD UNIX
Recall the getPID function introduced in Chapter 21:
getPID() { if [ $# -lt 1 ] ; then echo "ERROR: Insufficient Arguments." >&2 return 1 fi PSOPTS="-ef" /bin/ps $PSOPTS | grep "$1" | grep -v grep | awk '{ print $2; }' }
Remember that it works correctly only on systems where the command
ps ef
produces a listing of all running processes. This is not the case on Linux and BSD systems. On BSD systems, we need to use the command
ps auwx
to get the correct output. This works on older Linux systems, but on newer Linux systems an error message similar to the following is generated:
warning: '-' deprecated; use 'ps auwx', not 'ps -auwx'
By using the getOSName function given earlier in this chapter, we can adapt the getPID function to work with both the BSD and System V versions of ps. The modified version of getPID is as follows:
getPID() { if [ $# -lt 1 ] ; then echo "ERROR: Insufficient Arguments." >&2 return 1 fi case `getOSName` in bsd|sunos|linux) PSOPTS="-auwx" ;; *) PSOPTS="-ef" ;; esac /bin/ps $PSOPTS 2> /dev/null | grep "$1" | grep -v grep | awk '{ ⇒print $2; }' }
The two main changes are
In this chapter, you learned how to determine which version of UNIX you are running by using the uname command. In addition, you developed the getOSName and isOS functions to help you adapt your shell scripts to multiple versions of UNIX.
You also looked at the following techniques for improving the portability of shell scripts:
In conditional execution, you modify the flow of your script depending on the version of UNIX being used. In abstraction, you change the implementation of your functions to account for the differences between the versions of UNIX. Here, the flow of your script remains the same.
Using the techniques and tips in this chapter, you can port your shell script across different versions of UNIX.
Previous | Table of Contents | Next |