Lesson 7 | Making the script portable |
Objective | Use commands that are likely to run on different shells. |
Making Shell Script Portable
Early in this course you learned about different shells that are available on UNIX systems. The examples in this course use the Bourne shell, which is the oldest, least powerful shell. That's not why I chose it for this course, however. I chose it because the Bourne shell is available on virtually all UNIX systems. By writing shell scripts that run on all UNIX systems, you avoid the problem of needing to port your script to another platform where it may be needed. At least as far as the shell itself it concerned. In some cases, you may well choose to write a script for another shell that has features the Bourne shell lacks. When possible, however, it is a good idea to write your script using commands that are not specific to one shell.
Note: A free version of most shells is available for most UNIX systems, so your script can probably be run without actually converting it to another shell’s syntax if you have a little time to locate and install the correct shell on another new UNIX system.
Operating System Portability
A more important issue is the command set of the operating system. A shell script often uses operating system-specific utilities to retrieve information about files or complete other tasks. When the script is moved to another platform, these utilities are not available and the script fails.
The uname
command can be used to determine the version of UNIX on which the shell script is being run. By testing the output of this command, different commands can be selected within the script to collect system information, work with files, and so forth.
Often a separate procedure (a function) is used to complete a task in a shell script. The function can test which operating system is being used and select the correct commands to complete the task. The main body of the script that uses the function does not need to track which operating system is used.
Note: Creating functions within scripts is discussed in the course Advanced UNIX Shell Programming.
Script Portability and Error Trapping
Any programming project involves balancing the need for a secure, bullet-proof script with the need to finish the project on time and in budget; the need for quick development and the need to make the script flexible and portable might come up a year from now.
As you become more experienced at writing shell scripts, it will become easier to incorporate tricks for shell portability and bullet-proof code without using a lot of extra development time.
As you become more experienced, you will learn more tricks for shell portability and error trapping.
The next lesson discusses the importance of documenting your shell script.