CS/CE 218 Lecture -*-Outline-*- connection: so far we've looked at basics and building blocks of shell programs (statements), now we'll concentrate on more specialized techniques. * advanced shell programming advert: we see how to write polished shell programs, how to handle interrupts, and new ways to provide programs with input and to read input in the shell. it's also worth reading the manual page for sh to see other things... ** process id of current shell each shell has it's process id as the value of $$ --------------- $ echo $$ 16150 $ ps PID TTY TIME COMMAND 16184 ttyt0 0:00 ps 16150 ttyt0 0:01 sh --------------- Q: How do name a temporary file? use /tmp/cmdname.$$, for example Important so different copies of same program don't try to use same temporary file don't use /tmp/$0.$$, because $0 may be /home/cs218/cs218a23/bin/foo ** interrupts (pages 489-490) Interrupts (e.g., hangup, ^C) send signals so does the kill command Q: What is the default response of a shell script to a signal? to handle them otherwise, use trap ------------ # turn off interrupts trap '' 1 2 3 15 trap 'echo "$0: quitting early" >&2; exit 1' 1 2 3 15 ------------ 1=hangup 2=interrupt (^C) 3=quit (core dump, ^G) 15=software termination (kill command) You can even nest trap handlers: recall 0 is the file descriptor for stdin ------------ # get password from user if test -t 0 then # a terminal user trap 'trap "" 2 3 15; stty echo; exit 1' 2 3 15 stty -echo # turn off echoing echo "Password: \\c" read PASSWORD || { stty echo; exit 1; } stty echo # turn echoing back on trap 2 3 15 echo # echo user's newline else # not a terminal read PASSWORD || exit 1 fi ------------ note the \c string passed to echo makes no newline ** here documents (page 493) a way to get longish texts into a command's standard input in a way that allows for the various shell substitutions. Q: What is the standard input of try_hailstone below? ------------ try_hailstone <<-! n n $1 quit ! ------------ the - sign makes the leading white space stripped from the doc. Q: How would you do the above without using a here document? { echo n; echo n; echo $1; echo quit;} |try_hailstone (echo n; echo n; echo $1; echo quit) | try_hailstone explain { cmd-list; } vs. ( subshell ) idea $ echo $x $ (x=2) $ echo $x $ { x=2; } $ echo $x 2 Another syntactic form cat <