You can run commands in the background on your local machine by using nohup or appending & to your command. Both methods won't work if you run remote commands via SSH and expect it to send your SSH session to the background.

This is because while the command itself runs in the background, it will still block the SSH session and only exit once the command finishes executing.

Running a remote command automated via a script will not be efficient if it requires an active connection and fails to run in the background.

To execute SSH command remotely in the background without this issue, you need to prevent SSH from blocking for input by redirecting the output to /dev/null. You will then also need to send your SSH client session to the background.

You can achieve both effects by using the -n and -f options for the SSH client.

-n      Redirects stdin from /dev/null (actually, prevents reading from
        stdin).  This must be used when ssh is run in the background.  A
        common trick is to use this to run X11 programs on a remote ma‐
        chine.  For example, ssh -n emacs & will start an
        emacs on, and the X11 connection will be automat‐
        ically forwarded over an encrypted channel.  The ssh program will
        be put in the background.  (This does not work if ssh needs to ask
        for a password or passphrase; see also the -f option.)
     -f      Requests ssh to go to background just before command execution.
             This is useful if ssh is going to ask for passwords or passphrases,
             but the user wants it in the background.  This implies -n.  The
             recommended way to start X11 programs at a remote site is with
             something like ssh -f host xterm.

The following SSH command will run in the background on the server, and the session will immediately exit.

$ time ssh -fn "nohup sleep 10"
user@'s password: 

real	0m1.823s
user	0m0.008s
sys	0m0.003s
Discuss the article:

Comment anonymously. Login not required.