To perform tasks efficiently, you may need to execute remote commands on a server via SSH while also running other processes on your local machine. While the 'nohup' command and appending & to a command allow you to run background processes locally, these methods do not work as expected for remote SSH commands.

The issue is that even if a command runs in the background on the remote server, it continues to block the SSH session, only releasing it upon completion of the command. This behavior is problematic for automated scripts that require an active connection but fail to run the command in the background.

To execute a remote SSH command in the background without this limitation, follow these steps:

  1. Prevent SSH from blocking input by redirecting the output to /dev/null.
  2. Send your SSH client session to the background.

These objectives can be accomplished by using the -n and -f options with 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.

An example SSH command that will run in the background on the remote server while allowing the SSH session to exit immediately:

$ ssh -n -f user@remote_server 'command_to_execute > /dev/null 2>&1 &'

A simplified version like the example below does not suppress the output but will also work:

$ 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.