You can run commands in the background locally using nohup or by adding & to your command. Both methods won't work if you're running remote command via SSH because the command will block the session and only exit once the remote 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 remote ssh command in the background without this issue, you need to prevent SSH from blocking for input by redirecting the output to /dev/null and automatically run commands in the background.

You can connect to SSH server using -n option to redirect the output to /dev/null

-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 shadows.cs.hut.fi emacs & will start an
        emacs on shadows.cs.hut.fi, 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.)

You will then need to use -f option to run the command in the background.

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

Run your SSH command using both options and the command will run in the background without blocking the terminal.

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

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

Comment anonymously. Login not required.

Share!