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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top