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

Re: problem testing file descriptor 3



On Sun, Apr 10, 2005 at 11:33:32PM -0700, S. Cowles wrote:
> 
> 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

The -t flag tests to see whether an fd is open *and attached to a
terminal*.  So it's probably no good for what you need.

> 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.

I think that the only way you could do this would be using the stat
plugin.

    % zmodload -i zsh/stat
    % stat -f 3
    stat: 3: bad file descriptor
    % stat -f 3 3</etc/hosts
    device  365
    inode   8285
    mode    33188
    nlink   1
    uid     0
    gid     0
    rdev    32807
    size    177
    atime   1113201458
    mtime   1100873702
    ctime   1100873702
    blksize 4096
    blocks  4
    link

You should be able to make that do what you need.

-Dom



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