1

I try to have all my outputs redirected to a.out, except some that must also be written to b.out. I think using exec on top of tee (tee to also redirect to b.out) would be fine but tee does not look like always have the same behaviour (only the last one seems to work):

#!/bin/bash
exec > a.out
ls /boot |tee  b.out  #redirected to a.out only!
ls /var  |tee  b.out  #redirected to a.out only!
ls /run  |tee  b.out  #redirected to a.out only!
ls /home |tee  b.out  #redirected to a.out and b.out (good)
echo "a"              #redirected to a.out (good)

Same thing for ksh. For info, none of the ls cause an error. Why des tee sometimes fails to fork the output?

4

Every tee opens b.out on its own and overwrites it on its own. At the very end you see b.out from the last tee only (note this is independent from the previous exec, so the original question title "tee inside exec, random redirect behaviour" was rather misleading).

If you examined b.out between tee-s, you would notice it contains the output of the preceding tee only. You can do this by typing your commands one by one (without redirecting to a.out) and invoking cat b.out after each.

Redirection to a.out is somewhat different. When you exec, a.out is opened by the shell just once and everything that is redirected to it gets appended.

Solution: use tee -a. From man tee:

-a, --append
append to the given FILEs, do not overwrite

  • 1
    I feel bad for not even applying the simplest rule of code debugging - one line at a time. also, it was prety obvious that tee did not append but overwrote by default. Thanks, I will edit the question title as suggested. – Vulpo Mar 27 '18 at 7:58

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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