Unix Commands inside Shell Scripts



next up previous contents index
Next: Arithmetic in Shell Up: Shell Programs (Scripts) Previous: Case

Unix Commands inside Shell Scripts

Any Unix command or program may be executed from within a shell script by just issuing the command as you would on the command line. To ``capture'' or record the output of a command and assign it to a variable, the command is surrounded by forward quotes ` `. You have already encountered an example of this capture in the sample script for reading DOS floppies given in Chapter 3, Computer-Computer Interactions:


#!/bin/sh Use Borne shell. dosfiles=`dosdir notes` List DOS files on the floppy. for f in $dosfiles Repeat for each file name. do dosread -a notes/$f $f Read from floppy's directory notes. done

Although this script will do the job, there are two problems with it. The first is that while the dosdir command does list all DOS file names, it also produces a line stating how much free space is available:

% dosdir   	The AIX command.   
CONFIG.SYS   	   
CALL.EXE       	   
There are 216064 bytes of free space.   	   

Consequently, the script thinks this last line is part of the list of file names, but because the shell will be unable to locate any files with these names, it will complain to you. Accordingly, we filter out the last line by piping dosdir's output through egrep. The second problem is that the DOS file names are all in uppercase letters, and we prefer lowercase name for Unix files. To solve that problem, we use the tr tool described in § 5.1, Unix's Toolkit, to convert the file names to lowercase.

The improved script looks like this:


#!/bin/sh Script to strip off comments. dosfiles=`dosdir notes| egrep -v "bytes of free space"` for f in $dosfiles Repeat for each file name do lf=`echo $f|tr '[A-Z]' '[a-z]'` Set lf to lowercase name. dosread -a notes/$f $lf Read from floppy-directory notes. done



next up previous contents index
Next: Arithmetic in Shell Up: Shell Programs (Scripts) Previous: Case