0

I'm trying to start a long-running process on a remote server, over SSH:

$ echo Hello | ssh user@host "cat > /tmp/foo.txt; sleep 100 &"

Here, sleep 100 is a simulation of my long-running process. I want this command to exit instantly, but it waits for 100 seconds. Important to mention that I need the job to receive an input from me (Hello in the example above).

Server:

$ sshd -?
OpenSSH_8.2p1 Ubuntu-4ubuntu0.5, OpenSSL 1.1.1f  31 Mar 2020
yegor256
  • 102,010
  • 123
  • 446
  • 597
  • how will the command know there is no more input to arrive? does any output get produced that needs to be captured? – jhnc Aug 06 '22 at 11:36
  • @jhnc it knows this somehow after 100 seconds :) yes, all the output should be printed to me. – yegor256 Aug 06 '22 at 11:38
  • output locally or remotely? – jhnc Aug 06 '22 at 11:39
  • @jhnc what is "output locally" in this situation? All output is produced remotely and printed locally. Or I didn't understand the question? – yegor256 Aug 06 '22 at 11:43
  • 1
    if it is to be printed locally but you have terminated the ssh connection, how are you expecting the output to get back to you? – jhnc Aug 06 '22 at 11:44

1 Answers1

1

Saying "I want this command to exit instantly" is incompatible with "long-running". Perhaps you mean that you want the long-running command to run in the background.

If output is not immediately needed locally (ie. it can be retrieved by another ssh in future), then nohup is simple:

echo hello |
ssh user@host '
    cat >/tmp/foo.txt;
    nohup </dev/null >cmd.out 2>cmd.err cmd &
'

If output must be received locally as the command runs, you can background ssh itself using -f:

echo hello |
ssh -f user@host '
    cat >/tmp/foo.txt;
    cmd
' >cmd.out 2>cmd.err
jhnc
  • 11,310
  • 1
  • 9
  • 26
  • you are right, the problem was that the background job was "holding" the stdout and stderr streams. thanks! – yegor256 Aug 06 '22 at 12:05
  • @jhnc - in your first snippet, why do you need the `nohup`? It seems to be working without..? – YoavKlein Feb 28 '23 at 14:24
  • @YoavKlein You are correct. `nohup` may not be necessary in this situation (it would be needed if `ssh -t` were used, for example), but it is always safe to use `nohup` instead of trying to decide in any particular situation if sighup is expected. cf. https://stackoverflow.com/q/21294283/10971581 – jhnc Feb 28 '23 at 15:07