Bourne shell programming question...

matt at UCLA-LOCUS.ARPA matt at UCLA-LOCUS.ARPA
Sun May 13 20:23:20 AEST 1984


From:            "Matthew J. Weinstein" <matt at UCLA-LOCUS.ARPA>

>Date: 8 May 84 16:06:31-PDT (Tue)
>To: info-unix at BRL-VGR.ARPA
>From: hplabs!hao!seismo!cmcl2!rna!dan at ucb-vax.ARPA
>Subject: Bourne shell programming question...
>
>Article-I.D.: rna.250
>
>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 ?

1) Sh doesn't seem to handle redirection properly for read.  So, use a 
   program that reads one line from stdin and exits.  This could be the
   `head' program in 4.1:

	    READ="head -1"
	    ...
	    a=`$READ </dev/tty`

   The short C program:

	    #include <stdio.h>

	    main()
	    {
		int c;
		while ((c=getchar()) != EOF) {
		    putchar(c);
		    if (c=='\n') break;
		}
	    }

    also approximates a solution.

>	2) How do you arrange for a single instance of common shell code ?
>		The Bourne shell has no procedures and no goto statement.
>

2) Procedures are possible, but each one has to be a shell script (to
   the best of my knowledge).  Tricky scripts combined with eval can
   usually get some interesting results (nothing quite replaces local
   vars).

   Try something like:
   
	var='commands'
	...
	eval "$var"

   You can (sort of) pass params to this with the subterfuge:

	param1="blah.." param2="foo.." eval "$var"

   A short example:

	proc='for i in $arg; do 
	echo arg:$i ;
	done'

	arg="alpha beta gamma" eval $proc

	arg="A B C" eval $proc

   Note that `;'s etc. have to be in the right place here, since the
   multiples lines are scrunched together.  There may also be quoting
   losses.

This is all a bit ad-hoc (and it's late at night too).  Anyone have 
better suggestions (please!)?

						- Matt



More information about the Comp.unix mailing list