Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I would like to re-direct stdout half-way through a script. How can I do this in Zsh?

# Do something
# ... 

# Redirect stdout to a file (e.g. foo.txt)
for x in *;
print $x;
# Re-direct stdout back to default

# Do something else
# ... 
share|improve this question
up vote 5 down vote accepted

Use the exec builtin with a redirection but no command to redirect the shell's file descriptors. If you want to restore the original destination, you'll have to save it in another descriptor.

exec 3>&1 >foo.txt
for x in *; do
  print $x
exec >&3 3>&-

When the scope of the redirection is a portion of code, it is simpler to put the redirection around that piece of code.

for x in *; do
  print $x
done >foo.txt

If you want to apply a redirection to a sequence of instructions, put it inside braces.

  for x in *; do
    print $x
  echo 'one more line'
} >foo.txt

These constructs exist in all Bourne/POSIX-style shells, not just in zsh.

share|improve this answer
With a note that in the Bourne shell, redirecting a compound command causes a subshell, so it used to be desirable to use the exec 3>&1... there. Not anymore with modern shells. – Stéphane Chazelas Jan 23 '14 at 23:47
The docs on IO redirections for Bash: tldp.org/LDP/abs/html/io-redirection.html – slm Jan 24 '14 at 9:12

You can redirect the output of for easily enough with:

for foo in list; do
    somethingto $foo
done > /path/to/forloop_log.txt

This will only redirect the output of the for loop and not affect output before or after it.

You can accomplish the same thing for pretty much any command or set of commands by using a subshell:

( dosomethingelse; doyetanotherthing; ) > /path/to/special.log
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.