Search code examples
linuxshellsshnohup

'nohup 2>&1 >out' vs 'nohup >out 2>&1'


For me, the following two bash commands produce different results:

# returns instantly
ssh localhost 'nohup sleep 5 >out 2>&1 &'
# returns after 5 seconds
ssh localhost 'nohup sleep 5 2>&1 >out &'

It's surprising because the following two bash commands produce the same result:

# both return instantly
nohup sleep 5 >out 2>&1 &
nohup sleep 5 2>&1 >out &

Why?


Solution

  • This form:

    command >out 2>&1

    ... takes standard out and puts it to a file. It then takes standard error and puts it to the same location as standard out. Both streams are sent to a file.

    This form:

    command 2>&1 >out

    ... takes standard error and puts it on standard out. It then takes what would be sent to standard out and sends it to a file. It does not send standard error to the file.

    So, at your terminal, you are backgrounding the task and the prompt returns immediately. When using ssh, in the first case, there is no output to display because everything has been sent to a file. In the other case, standard out can still display information that the application tries to send to standard error.

    My expectation is that ssh returns immediately in the first case because there will never by any output. In the second case, there is an open stream that may return data for you to see.