How to redirect all stderr in bash?

Tags: shell bash linux

I'm looking for a way to redirect all the stderr streams in interactive bash (ideally to its calling parent process).

I don't want to redirect stderr stream from each individual command, which I could do by appending 2> a_file to each command.

By default, these stderr streams are redirected to the stdout of an interactive bash. I would like to get them on the stderr of this interactive bash process in order to prevent my stdout to be polluted by error messages and be able to treat them separatly.

Any ideas?

I still haven't found an answer ... But maybe it's actually a tty parameter. Does anybody knows something about tty/interactive shell responsibility for handling stderr ?


I find a good way is to surround the commands by parentheses, '()', (launch a sub-shell) or curly-braces, '{}' (no sub-shell; faster):

} 2> error.log

Of course, this can be done on 1 line:

{ cmd1; cmd2; ... cmdN; } 2> error.log
By : stefano

Two things:

  1. Using 2>&1 in a remote ssh command results in the error ending up inside the local tarfile, resulting in a 'broken' backup.
  2. If you want to apply a redirect on the other side of the ssh, remember to escape the redirect command.

My suggestion would be to redirect stderr on the remote side to a file and pick it up later, in case of an error.


ssh -t remotehost tar -cf - /mnt/backup 2\>backup.err > localbackup.tar
if [ $EXITSTATUS != "0" ] then 
  echo Error occurred!
  ssh remotehost cat backup.err >localbackup.errors
  cat localbackup.errors
  ssh remotehost rm backup.err 
  echo Backup completed successfully!
  ssh remotehost rm backup.err 

Tried ssh -t to create a pseudo-TTY at the remote end?

By : crb

This video can help you solving your question :)
By: admin