Sams Teach Yourself Shell Programming in 24 Hours
(Publisher: Macmillan Computer Publishing)
Author(s): Sriranga Veeraraghavan
ISBN: 0672314819
Publication Date: 01/01/99
Summary
In this chapter, I presented a library of shell functions that can be used in your shell scripts to handle many common tasks. By using and improving these implementations, you can avoid having to reinvent the wheel when faced with a particular problem.
Some of the problems that I addressed are
- Displaying standardized error, warning, and usage messages
- Prompting for a yes or no response
- Prompting for a general response
- Checking disk space
- Getting the process ID of a command using its name
- Getting the numeric user ID of a user
In addition to these tasks, I have covered many other useful functions throughout this book. By using these functions, you can concentrate on developing scripts to solve complicated problems without worrying about the basics.
Questions
- 1. Write a function called toLower that converts its arguments to all lowercase and displays the converted string to STDOUT. You dont have to worry about checking the number of arguments.
(HINT: Use the tr command.)
- 2. Write a function called toUpper that converts its arguments to all uppercase and displays the converted string to STDOUT. You dont have to worry about checking the number of arguments.
(HINT: Use the tr command.)
- 3. Write a function called isSpaceAvailable to check whether a directory contains a certain amount of disk space.
Your function should accept two arguments. The first one indicates the directory to check, and the second one indicates the amount of space to check. An error should be reported if both arguments are not given. Your function should validate that the first argument is a directory.
If sufficient space is present, your function should return 0; otherwise, it should return 1. This enables us to use it as follows:
if isSpaceAvailable /usr/local 20000 ; then
: # perform some action
fi
(HINT: Use the function getSpaceFree.)
- 4. Modify your isSpaceAvailable function to accept an optional third argument that specifies the units of the amount space to check.
The default should remain in kilobytes, but you should support m or mb indicating megabytes and g or gb indicating gigabytes. If some other units are given, assume that the user meant kilobytes.
The following conversion factors apply to this problem: 1MB equals 1024KB, and 1GB equals to 1024MB.
(HINT: Use the bc command.)
- 5. Write a function called isUserRoot that checks to see whether the ID of a user is equal to 0. If no user is given, it should check to see whether the ID of the current user is root.
(HINT: Use the getUID function.)
Terms
- Library
- A file that contains only functions is called a library. Usually libraries contain no main code.
- Main Code
- Main code consists of all the commands in a shell script that are not contained within functions.