Question

Something funky I gathered from the zsh man pages, is how you can redirect stdout and stderr to somewhere else, e.g. a file. It works like this:

logfile=/tmp/logfile

# Create a file descriptor and associate it with the logfile
integer logfd
exec {logfd} >> ${logfile}

echo "This goes to the console"
echo "This also goes to the console" >&2
echo "This goes to the logfile" >&{logfd}


# Now redirect everything to stdout and stderr to the logfile
# No output will be printed on the console
exec >&${logfd} 2>&1


print "This goes to the log file"
print "This also goes to the log file" >&2

For completeness' sake, a file descriptor can be closed by issuing exec {logfd}>&-.

I can just not figure out one thing. How do you reset zsh's redirections so that further output is again printed just to the console?

Was it helpful?

Solution

Found it after I issued ls -l /proc/self/fd/. Apparently there is a file descriptor 0 that can be used, it points to the console.

So, first we redirect back to that file descriptor:

exec >&0 2>&1

And now the log file can be safely closed:

exec {logfd}>&-

Ideal for scripts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top