Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

problem testing file descriptor 3



I am having trouble testing if file descriptor 3 is already opened in the
calling environment.  If the file descriptor is not open, I would like to
open it and redirect it to stderr.  The test script I am using is:

	#!/bin/zsh
	[[ -t 3 ]] &&
		{ echo "fd3 is open."; } ||
		{ echo "fd3 is not open."; }
	echo no1 >&1
	echo no2 >&2
	echo no3 >&3
	exit 0

If the script is invoked in this manner:
	cp /dev/null fd3.out
	exec 3>&-
	./test 3> fd3.out
the script reports that fd3 is not open even though fd3 output does correctly
redirect to the file fd3.out.

If the script is invoked like so:
	exec 3>&-
	exec 3> /dev/tty
	./test
the script reports that fd3 is open and all output correctly appears on the
terminal session.

If I use a test like this:
	echo -n "" >&3 1> /dev/null 2> /dev/null || {
		echo "fd3 is not open."
		exec 3>&2
	}
error messages are not hidden.

So, as a recap, if fd3 is already opened when the script is called, I want
output to redirect as coded in the calling environment.  If fd3 is not
already opened, I want to redirect fd3 output to an existing, open fd and
I want any error messages hidden.

What is a good test to determine if file descriptor 3 is open in the calling 
environment?  Thanks.

Full test example:

$ cat ./test;
echo;
cp /dev/null fd3.out; exec 3>&-; ./test 3> fd3.out; head fd3.out /dev/null;
echo;
exec 3>&-; exec 3> /dev/tty; ./test;
#!/bin/zsh
[[ -t 3 ]] &&
	{ echo "fd3 is open."; } ||
	{ echo "fd3 is not open."; }
echo no1 >&1
echo no2 >&2
echo no3 >&3
exit 0

fd3 is not open.
no1
no2
==> fd3.out <==
no3

==> /dev/null <==

fd3 is open.
no1
no2
no3
$




Messages sorted by: Reverse Date, Date, Thread, Author