Ssh – Direct stderr to a file over ssh

io-redirectionsshstderr

I am trying to execute a command on a local machine and direct the stderr to a remote machine over ssh. I cannot do

 ssh remote machine "command 2>stderr.log"

because the remote machine doesn't have the correct built to execute the command, and I have to run the command on my local machine. I haven't tried it yet but I am mostly positive that we can't do 2>ssh local machine /dir/stderr.log?

Best Answer

As I understand it, you want to run a command locally but save the stderr output to a remote log file.

Try process substitution:

local_command 2> >(ssh somemachine 'cat >logfile')

Here, >(...) is process substitution. It creates a file-like object from the command in the parens. So, 2> redirects stderr to that file-like object, resulting in the output being saved on the remote machine.

Or, just use plain old redirection:

{ local_command 2>&1 1>&3 | ssh somemachine 'cat >logfile'; } 3>&1

Here, stderr is redirected to stdout so that we can pipe it to ssh. So that stdout does not go to ssh, we redirect it to file handle 3. At the end of the command, file handle 3 is redirected to stdout so that it appears on the terminal.

Related Question