Lost Assignment of var in shell for loop with stdout redirection

dce at mips.UUCP dce at mips.UUCP
Sat Feb 7 00:33:37 AEST 1987


No, this is not considered to be a bug. When you do redirection or pipes
of any kind, the shell forks. This is done because getting back to the
original file state would be impossible if you tried to do it locally.

Basically, it would be almost impossible to handle the case in which
you execute

	shell_script < foo > bar

if there was some internal redirection inside of the shell script.
The shell couldn't save the file descriptors somewhere else because
it would run out of descriptors (ever hear of the 'fd>file' syntax?).
Thus, the shell has to fork to the the redirection.

Now, if your problem is that you need a way to assign a variable
during a redirection and have that value available afterwards, you have
a couple of possibilities:

	1. Place the variable value in a file, and use

		VAR="`cat file`"

	2. You can get tricky, as in

		#!/bin/sh
		exec 9>&1	# save stdout in fd 9
		exec 1>bar	# stdout->file "bar"
		for i in 1 2 3 4 5
		{
			var="$i"
			echo "hello"  # output goes in file "bar"
		}
		exec 1>&9	# stdout->saved stdout
		echo "$var"

	   I use file descriptor 9 here to stand out, but I believe that
	   all file descriptors other than 0, 1, and 2 are closed upon
	   execution of subprocesses, so you should be able to use anything
	   from 3 to 9 (2-digit fds are syntax errors). Can Guy or Doug
	   or someone verify this?
-- 
			David Elliott

UUCP: 	{decvax,ucbvax,ihnp4}!decwrl!mips!dce, DDD:  	408-720-1700



More information about the Comp.unix.questions mailing list