I want cron to only mail stderr output, while simultaneously log stdout+stderr, in correct order, to a file.

I have been fiddling with tee and the likes, but not quite got it right...

It's ok to wrap the command into a shell script


mycommand | maybe_some_shell_redirect_magic >> /var/log/mycommand.log
  • It's difficult to understand what do you want exactly. Please, clarify the question. – Bob Aug 21 '18 at 14:42

I think it's possible - while keeping line ordering (ie. stderr is copied from within the process where it is written to), even with a POSIX shell. Try :


exec 3>log
command args ... 2>&1 >&3 |while read err; do
  echo "$err" >&2
  echo "$err" >&3

It's not possible to keep the order accurately while separating stdout and stderr. You can get reasonable results with this as long as the timing of stdout and stderr outputs is not too close:

mycommand 2>>/var/log/mycommand.log | tee -a /var/log/mycommand.log

You can test it with this script in place of mycommand:

echo stdout 1
sleep 0.1
echo stderr 1 >&2
sleep 0.1
echo stdout 2
sleep 0.1
echo stderr 2 >&2

If you remove the sleep commands, the order in the log file will be somewhat messed up though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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