Linux for Programmers and Users

[Page 290 (continued)]

7.13. Sample Project: junk

To illustrate some of the Korn shell capabilities, I present a Korn shell version of the "junk" script project that was suggested at the end of Chapter 6, "The Bourne Again Shell." Figure 7-44 defines the junk utility about to be described.

Figure 7-44. Description of the junk shell script.

Utility: junk -lp { fileName ]*

junk is a replacement for the rm utility. Rather than removing files, it moves them into the subdirectory ".junk" in your home directory. If ".junk" doesn't exist, it is automatically created. The -l option lists the current contents of the ".junk" directory, and the -p option purges ".junk".

The Korn shell script that is listed below (and available onlinesee the Preface for more information) uses a function to process error messages, and uses an array to store filenames. The rest of the functionality should be pretty easy to follow from the embedded comments.

7.13.0.1. junk

#!/bin/ksh # junk script # Korn shell version # author: Graham Glass # 9/25/91 # # Initialize variables # fileCount=0 # the number of files specified. listFlag=0 # 1 if list option (-)used. purgeFlag=0 # 1 if purge (-p) option used. fileFlag=0 # 1 if at least one file is specified. junk=~/.junk # the name of the junk directory. # error () { #


[Page 291]
# Display error message and quit # cat << ENDOFTEXT Dear $USER, the usage of junk is as follows: junk -p means "purge all files" junk -l means "list junked files" junk <list of files> to junk them ENDOFTEXT exit 1 } # # Parse command line # for arg in $* do case $arg in "-p") purgeFlag=1 ;; "-l") listFlag=1 ;; -*) echo $arg is an illegal option ;; *) fileFlag=1 fileList[$fileCount]=$arg # append to list let fileCount=fileCount+1 ;; esac done # # Check for too many options # let total=$listFlag+$purgeFlag+$fileFlag if (( total != 1 )) then error fi # # If junk directory doesn't exist, create it # if [[ ! (-d $junk) ]] then
[Page 292]
'mkdir' $junk # quoted just in case it's aliased. fi # # Process options # if (( listFlag == 1 )) then 'ls' -lF $junk # list junk directory. exit 0 fi # if (( purgeFlag == 1 )) then 'rm' $junk/* # remove files in junk directory. exit 0 fi # if (( fileFlag == 1 )) then 'mv' ${fileList[*]} $junk # move files to junk dir. exit 0 fi # exit 0

Here's some sample output from junk:

$ ls *.ksh ...list some files to junk. fact.ksh* func5.ksh* test.ksh* trap.ksh* func4.ksh* squares.ksh* test2.ksh* $ junk func5.ksh func4.ksh ...junk a couple of files. $ junk -l ...list my junk. total 2 -rwxr-xr-x 1 glass apollocl 205 Feb 6 22:44 func4.ksh* -rwxr-xr-x 1 glass apollocl 274 Feb 7 21:02 func5.ksh* $ junk -p ...purge my junk. $ junk -z ...try a silly option. -z is an illegal option Dear glass, the usage of junk is as follows: junk -p means "purge all files" junk -l means "list junked files" junk <list of files> to junk them $ _

Категории