You can run command in the background locally by using nohup or by adding & to your command. This won't work if you're running remote command via SSH because the command will block the session and will only exit once the remote command finish executing.

This might not be acceptable if you're running a remote command automated via a script.

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"
[email protected]'s password: 

real	0m1.823s
user	0m0.008s
sys	0m0.003s

Support us on Patreon if this guide has helped you. Thanks!!!

Discuss the article:

Comment anonymously. Login not required.

Share!