gripes about /bin/sh AND /bin/csh

chris at umcp-cs.UUCP chris at umcp-cs.UUCP
Mon Jun 16 08:18:12 AEST 1986


In article <44 at houligan.UUCP> dave at smaug.UUCP (Dave Cornutt) writes:
>What Phil wants (me too) is some capability to open a file in a sh/csh
>script and read a line at a time into a variable, like this:
>	open <some-file> xyz
>	while ( ! eof(xyz) )
>		read xyz $line_from_file
>		<...do stuff with data...>
>	end
>	close xyz
>Neither sh nor has any such capability.

I assume you mean `neither sh nor csh'.  Well, you can fake it in
csh, but it is easy to do in sh:

	while read x; do
		echo "input line: $x"
	done < file

If you need to read stdin as well it gets harder; and it becomes
much harder if you want the loop to affect a shell variable that
can be tested outside the loop, for the loop is run in a fork.
However, if all else fails you can always write a temporary script
and source it:

	# set these based on SysV/BSD flavour
	# as Larry Wall has demonstrated, this can even be done dynamically
	# n=; c=\\c	# SysV
	n=-n; c=	# BSD
	tf=/tmp/ugly.$$; rm -f $tf; trap 'rm -f $tf' 0 1 2 3 15
	while read line; do
		case "$line" in
		...
		something_fancy)
			flag=true		# set the flag
			echo "flag=true" >$tf;;	# and record it
		another_fancy_thing)
			echo $n "foo? " $c	# ask a question
	# Getting the answer is harder, for `read' will not accept
	# redirection.  The simplest solution is a program that reads
	# one line from stdin and echoes it:
	#		answer="`gets 0<&3`"	# and read stdin for answer
	# Unfortunately, `gets' is gone in 4.3.  `head -1' works; but
	# the following should even be portable:
			answer=`sh -c "read input; echo \"\\\$input\"" 0<&3`
			case "$answer" in
			y|yes|indeed|sure|ok|yup|fine)	# add others as desired
				echo "can run commands too" >$tf;;
			esac;;
		...
		esac
	done 3<&0 <file
	# now regain any effects lost after the loop, and do other tricks
	. $tf

For completeness, the line that reads stdin should run the output
through `tr' to translate to lowercase (or the case below that
should list all, er, cases: rather tedious).  I left that one out
because SysV changed `tr' to be incompatible with V7 derivatives,
and more of the magic `compatiblisation' code like the `echo'
command just seemed to me to be overkill.
-- 
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 1516)
UUCP:	seismo!umcp-cs!chris
CSNet:	chris at umcp-cs		ARPA:	chris at mimsy.umd.edu



More information about the Comp.unix mailing list