Shell lecture notes, pt2
Write the following shell scripts.
In your shell
scripts, you may only use the following:
- Any internal shell command (e.g. echo, for, etc).
- cat, head, tail, sort, bc,
sleep, kill, expr.
You may not write any C programs to help yourself out,
nor are you allowed to use any other Unix programs (like sed
or perl) in your scripts.
You should not have to create any temporary files. But if you do so,
ensure that the temporary files and ONLY the temporary files are removed
when you are done.
If the program specifications require you to prompt the user, do so.
If the specification does NOT say to prompt the user, DO NOT. Try not to
add extraneous information to the output of your programs. It makes it
difficult to grade. For instance extra lines that are not specifically
required.
Finally, your program should handle errors gracefully. For example,
if the command line arguments are supposed to be files, and the user
specifies a non-file, you should print a descriptive error message on
standard error, and either exit or not exit as you see fit.
The first 3 exercises are mandatory. I highly recommend that you at least
give the other 3 a serious attempt. I will provide answers to all of them
next week.
Required problems:
- revarg: This script prints out its command line arguments
in reverse order all on one line.
- sortfl: This script treats the command line arguments as
filenames. It sorts the filenames, and then for each file, it prints
the file's name, the first line of the file, the last line of the file,
and a blank line.
- lsfiles: This script takes a list of files as its command
line arguments. For each file, it first prints out the file's name,
then it prints out any word in the file that is the name of an existing
file (or directory) in the directory. Then it prints out a blank line.
Recommended Problems:
- lsnums: This script prints out a sorted list of all words
in standard input that can be treated as non-zero numbers. Make the
list sorted numerically, not lexicographically.
- square: This script takes a number as its command line
argument. Call this number n. The script prints out lines
of the form
``i i*i''
where "i*i" is the square of i for each i from zero to n.
- mytimex: This script takes a shell command on its command
line argument, and executes it in the background. It then waits one
minute, and if after one minute, the command has not exited, it kills
it with kill -9. You'll have to use kill to determine
if the process is still alive (read the man page). You cannot
use ps or write your own C program to test for the existence of
a process.
Additionally, you should be able to call mytimex in the following
manner:
mytimex -t sec command
This has mytimex sleep for sec seconds instead of 60.
Don't worry about preserving multi-word arguments (i.e. arguments
with spaces in them) when you execute the command. In other
words, if I say
mytimex echo 'John Smythe'
it's ok if the output is
John Smythe