These shell scripts were taken or slightly modified from the NewKorn shell book, the Unix for Users and Programmers by Glass The UNIX C shell field guide and other sources. korn shell examples This is a sample list of shell scripts that we executed in class. FUNCTIONS: instr.affirmative ======== I placed affirmative in my .profile rather than setting an environment variable FPATH for ksh to find the function These are the steps I used to demonstrate in class . $HOME/.profile at the prompt type: $while affirmative 'Do you want to continue?' do ls done affirmative ======== function affirmative { typeset reply while true do read -r "reply?$1? " || return 1 case $reply in y|yes) return 0;; n|no) return 1;; *) print 'please answer y or n' ;; esac done } fact2.ksh ======== fact2() { if (( $1 <= 1)) then echo 1 else typeset tmp typeset result (( tmp = $1 -1)) (( result = `fact2 $tmp` * $1)) echo $result fi } Instructions for running factorial: make sure your FPATH environment is set for your ksh to find the file where the function is located. factorial 3 echo factorial 3 = $? func.ksh ======== factorial() { if (( $1<=1)) then return 1 else typeset tmp typeset result (( tmp = $1 - 1)) factorial $tmp (( result = $? * $1)) return $result fi } testfile used for co-process in the ksh ======== this is the first line I like to go swimming I have office hours on Thursdays I am done coprocess ======== ed - testfile |& print -p swimming read -r -p line print -r -- "$line" instr.for ======== for.ksh mailfile menu.ksh mailfile ======== this is a test menu.ksh ======== #!/bin/ksh PS3="Select the item number:" file=mailfile select event in Format Page View Exit do case "$event" in Format) nroff $file ;; Page) pr $file ;; View) cat $file;; Exit) exit 0;; *) echo "Invalid selection";; esac done for.ksh ======== #!/bin/ksh for file do ls -l $file done if.ksh ======== #!/bin/ksh if print "Please enter your name: \c" read -r name then if mail "$name" < mailfile then : else print "Cannot mail to $name" fi else print 'end-of-file' exit 1 fi trap.sh ======== #!/bin/ksh for i in * do cat $i >> tmp.$$ ls -l $i >> tmp.$$ wc -l $i >> tmp.$$ done trap 'rm -f tmp.$$; exit ' 0 1 2 15 trap2.sh ======== #!/bin/ksh for i in * do cat $i >> tmp.$$ ls -l $i >> tmp.$$ wc -l $i >> tmp.$$ done trap 'echo cleaning up ' EXIT trap 'rm -f tmp.$$ ' EXIT =================================== csh examples =================================== dirlister ======================= #!/bin/csh # dirlister # usage dirlister dir(s) if ($#argv == 0) then #no arguments echo "Usage $0 dir1 ... dirn" # error message and exit 1 # exit endif while ($#argv) # while there are arguments if (-d $argv[1]) then # directory? ls -l $argv[1] | pr -h $argv[1] # list and format else echo $0\: No directory $argv[1] # display error endif shift # get next argument end ============== if.csh =============== # csh to greet you in your .loginfile set d=`date` echo "Today is $d[1]" if ($d[1] == Fri) then echo =================== echo Timesheets due! echo =================== endif unset d ============== ifelse.csh =============== # csh to greet you in your .loginfile set d=`date '+%H %a'` if ($d[1] < 12) then echo -n Good morning else if ($d[1] <= 18) then echo -n Good afternoon else echo -n Good evening... endif echo " Today is $d[2]" if ($d[2] == Fri) then echo =================== echo Timesheets due! echo =================== endif unset d loc =============== # # loc: quick and easy find # assumes home directory unless specified # usage loc [dir] filename # set noglob # prevent file expansion set com = $0 if ($#argv < 1 || $#argv > 2) then # check arguments echo "Usage: $com:t [path] filename" # only one or 2 allowed exit 1 endif if ($#argv == 2) then # if 2 then path specified set p = $argv[1] shift # remove first argument else set p = $HOME # use home dir as default endif if ( ! -d $p:q) then # check for directory echo "$com:t: no directory $p" exit 1 endif set tf = /tmp/$com:t.$$ # set up tmpe file #throw away disagnostic output; standard output in $tf ((find $p -name $argv[1] -print| tee $tf)>/dev/tty) >& /dev/null if (-z $tf) then echo "$com:t Can't find $argv[1]." # failure message rm -f $tf # rm temp file exit 1 endif rm -f $tf # rm temp file exit 0 # normal exit =============== lscripts =============== # this file has syntax errors #list script files # usage: lscripts files(s) if ($#argv == 0 then echo "Usage lscripts file (s)" exit 1 endif foreach f ($#argv[*]) if (-e f) then set sc= `file $f| grep "commands text" if ($#sc == 0) then echo $f: yes else echo $f: no endif else echo "file $f does not exist." endif end numfiles =============== #counts number of files and directories in argument 1 or current directory # usage numfiles [ directory] if ($#argv == 0) then # no arguments? set dir = "." # use current directory else set dir = $argv[1] # use argument 1 endif if (-d dir) then # not a directory? echo $0\: $dir is not a directory # error message and exit 1 # exit endif echo $dir\: # echo directory name @ fcount = 0 # initialize counters @ dcount = 0 cd $dir # change dir to $dir foreach file (*) # file expansion if (-f $file) then # file? @ fcount++ # increment file counter else if ( -d $file) then # directory? @ dcount++ # increment directory counter endif end echo $fcount files $dcount directories # display results onintr =============== # this is not a complete shell script, extracts from a shell # script to demonstrate how onintr can be used onintr catch # process interrrupts set com=$0 set tf= /tmp/$com:t.$$ # temp filename sort +1 -d -f $file > $tf # sort in foreground nroff -ms app. * > appendix& # format in background set job1 = $child exit 0 catch: rm -f $tf # rm temporary file if ($?job1) then # job1 defined? kill -9 $job1 # terminate background job endif exit 1 # error exit =============== startup =============== Key parts of a .login: #Comments begin with pound sign # # Standard .login file for Suns and VAXes (Understands optional # tcsh features) # Tony Movshon 2/17/91 # Includes a "source .login.$HOST" for customization # Includes optional startup of OpenWindows or Sunview # if ($?TERM) then if (($TERM == su) || ($TERM == dialup) || ($TERM == micom) || ($TERM == network)) then set noglob eval `tset -sQ -m su:?vt102 -m dialup:?vt320 -m micom:?vt320 -m network:?vt100` unset noglob endif endif if ($TERM == unknown) then setenv TERM vt100 stty erase '^H' stty erase '^?' biff n endif setenv EDITOR /usr/ucb/vi setenv PRINTER ap4 #set the paths setenv MANPATH /usr/lang/man:/usr/man:/usr/local/man:/usr/math/man setenv TROFF /usr/local/bin/psroff setenv TEKCOPY "/usr/local/bin/pssun -S 8.0 | lpr" #print out messages echo "Port: $PORT" echo "Terminal: $TERM" echo "If terminal is unknown, type setenv TERM vt100" echo "" ------------------ now .cshrc -------------- if ($user != root) \ set path=(. ~/bin \ /usr/motif/bin /usr/local/bin\ /griffin.a/griffin/new/bin \ /usr/csh/bin /usr/lang /usr/bin/X11 \ /usr/hosts /usr/local2/lib/frame-OpenLook/bin \ /usr/local2/lib/frame-X/bin /usr/local2 /usr/export/local \ $IOFFICE/bin /usr/ucb /usr/games /bin /usr/local \ /usr/bin /etc /usr/etc \ /usr/openwin/bin \ /usr/export/local/druid/druid2.0/bin \ ) users =============== #!/bin/csh set user=(alice bob carol ted) while ($argv[1] != $user[1]) # cycle through each user, checking for a match shift user # if we cycled through with no match ... if ($#user == 0) then echo "$argv[1] is not on the list of users" exit 1 endif end echo "$argv[1] is in $user" wmail =============== # csh script to send mail or converse with a user # usage wmail username set w = (`who|grep $argv[1]`) if ($#w == 0) then echo "$argv[1] is not logged in .. send mail" mail $argv[1] else echo "$argv[1] logged in ... let's talk" write $argv[1] endif ======================================== grep/egrep/fgrep examples addphone ========== echo $1 >> phonebook alphvowels ========== ^[^aeiou]*a[^aieou]*e[^aeiou]*i[^aieou]*o[^aeiou]*u[^aieou]*$ egrep ========== egrep -f monotonic /usr/dict/words | grep '.....' egrep2 ========== egrep -f alphvowels /usr/dict/words | pg grep ========== grep '^From' $MAIL grep '^From' $MAIL | grep -v lahmani grep '^From' $MAIL | grep -vi lahmani monotonic ========== ^a?b?c?d?e?f?g?h?i?j?k?l?m?n?o?p?q?r?s?t?u?v?w?x?y?z?$ myphone ========== grep $1 phonebook phonebook ========== danielle 3456767 charles 6785454 regular ========== regular expressions used with grep and egrep pattern what does it match bag ^bag bag$ ^bag$ [Bd]ag b[aeiou]g b[^aeiou]g b.g ^. . .$ ^\. ^\.[a-z][a-z] ^[^.] bugs* [A-Z][A-Z]* [A-Z]+ egrep only [A-Z].* [A-Z]* [a-zA-Z] [^a-zA-Z] str2 ========== xyxyxyxy xyyyyyy xxxxxxxxxxx yyyyyyyyyyy strings ========== abc accolade ambiance abab abort workable