[prog] Shell question...

Namik Dala namik.dala at web.de
Sun Dec 12 04:26:58 EST 2004


On Thu, Dec 09, 2004 at 10:13:58PM +0100, Riccarda Cassini wrote:
> I've got a bunch of ksh scripts that were nicely doing their job under
> HP-UX, for ages.  Now, I'm supposed to add some more functionality,
> and, while I'm at it, port them to Linux.  Easy, I thought - but at the
> moment I'm stumbling over constructs of the form
> 
>   echo bla blah blurb | read FOO BAR BAZ

This is a well known problem in shell programming. There are some
workarounds:

	var=$(echo bla blah blurb)
	set -- $var
	FOO=$1; BAR=$2; BAZ=$3

or

	read FOO BAR BAZ << EOT
        bla blah blurb
        EOT

There is another one. It is usefull when reading in a while read
loop and you want to keep the values of the last iteration.

	someprog | while read a b c ;
	do
	  # do something with a and break
	  break
	done
	echo $a $b $c

a, b and c will be empty. Solution is a named pipe (this should
work in every shell) or a co-prozess for ksh programming:

	# named pipe, portable way
	mkfifo /tmp/fifo.$$ # you should use mktemp
	someprog > /tmp/fifo &
	while read a b c;
	do
	...
	done < /tmp/fifo
        rm /tmp/fifo.$$

        #co-prozess (ksh)
        someprog |&
        while read -p a b c;
        do
        ...
        done 

Weill, I don't know why this is not happening with your HP-UX
ksh, maybe it executes the command which is writing into the pipe
in a subshell.

						-Namik-


More information about the Programming mailing list