sshsshd

How to ask a remote server over SSH to run a background job?


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

Solution

  • 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