Bourne shell programming question...

merlyn at sequent.UUCP merlyn at sequent.UUCP
Tue May 15 03:01:12 AEST 1984


> From: dan at rna.UUCP
> Message-ID: <250 at rna.UUCP>
> Date: Tue, 8-May-84 16:06:31 PDT
> 
> Hi,
> 	I've just started to use the Bourne shell in non-trivial
> command script writing and have run into a number of problems. I am
> converting some shell scripts from an older shell (V6-like with variables).
> 	In particular,
> 	1) How do you read a single line from /dev/tty (or an arbitrary file,
> 		NOT stdin) and assign that line to a variable ?
> 	2) How do you arrange for a single instance of common shell code ?
> 		The Bourne shell has no procedures and no goto statement.

First, number 2.  Can't, at least not without stashing it in a separate file
and calling it as a subroutine (very icky).  Also, they call up (at least)
one more process.  Time consuming on most Un*xes.

Second, number 1.  I agree that your solutions leave lots to be desired.
Bourne himself in his (not real great) book "The Unix System", gives this
flavor of a solution:

	exec 3<&0 </dev/tty
	read foo
	exec <&3 3<&-

if you can believe that.  For a bit of explanation, this maximal esotericism
does the following:

	(1) the first line copies stdin (whatever that is) to file descriptor
	"3" (the first one after stdin=0, stdout=1, and stderr=2), and
	at the same time, reopens stdin to be /dev/tty.  This is all done
	without starting a new process... exec is one of the few builtins
	that allows I/O redirection.

	(2) the second line does the read into shell variable "foo" from
	/dev/tty.

	(3) the third line copies file descriptor 3 back to stdin, and then
	closes file descriptor 3.

I kinda like this one, since it doesn't use any new processes.  But,
only the author of the Bourne shell (and a very esoteric one at that) would
resort to coming up with such bizarre uses for that little-used feature
of assigning specific file descriptors to specific files.  [Slight editorial
comment.]

Another favorite, although it still needs a separate process is
	foo="`head -1 /dev/tty`"
but you have to be using a Berkeley Un*x to take advantage of that.
(You could write a quicky C program to do the same thing.)

-- A particularly personal and original observation from the thought-stream of
Randal L. ("</dev/null >&0 2>&1") Schwartz, esq. (merlyn at sequent.UUCP)
	(Official Legendary Sorcerer of the 1984 Summer Olympics)
Sequent Computer Systems, Inc. (503)626-5700 (sequent = 1/quosine)
UUCP: {decwrl,ogcvax,pur-ee,rocks34,shell,unisoft,vax135,verdix}!sequent!merlyn

P.S. Unix is a trademark of some divested part of TPC.  (Who owns that now?)

P.P.S.  I have no personal gripes with Bourne.  I just happen to notice that
some of the things that he does are a bit odd.  "Pay no attention to the man
behind the curtain."



More information about the Comp.unix mailing list