If I connect to a remote database server via ssh, start mysql client and execute a query which may take a couple of hours to execute, then close the connection, will the query continue to execute until completed? Can I mysqldump in this way on a huge database, go back a few days later and expect it all to be complete?



Simply put: no - unless you take special measures, any long lived commands on the server will terminate when the shell that ssh started remotely exits. That shell will exit if you terminate your ssh session, or even if the TCP connection is broken (lose network connectivity, switch wifi networks, hibernate, etc).

However, there are several options to accomplish those "special measures". From simplest to most complex/involved:

  • nohup - simply prepend your one-line command with nohup. This works if you can assume that the command will execute and then terminate itself. Output will be sent to the nohup.out file in your current directory. Example:

    nohup sh -c "sleep 5; echo done" &
  • screen - screen will setup a virtual terminal window that will not exit when your ssh connection terminates. You can reconnect to the server at a later time and see the status of any commands you were running and issue new commands. Example:

    % client: ssh server
    # server: screen
    # server[0]: mysql -e 'really long query'

    The later come back and:

    % client: ssh server
    # server: screen -RD  # -RD says "reconnect to my previous screen, even it already attached"
    # server[0]: <right where you left off in the previous screen>

    There are lots of options to screen, you can create several "terminals" inside of one screen session, and you can configure it extensively in the file ~/.screenrc.

  • mosh - a replacement for ssh which will maintain the session regardless of network connectivity. As you migrate between wifi networks, or even hibernate/awaken your machine, mosh will reconnect to the server. Additionally, it will provide a lag free interface to work through, so as you type your commands, you not be affected by link or server slowness. Note that mosh uses ssh to establish the initial connection and setup the UDP server on the remote end.

| improve this answer | |

Closing the SSH connection will end any processes started within that session.

Take a look at the screen command, wich let's you start a session within a shell then reconnect to it later from another local or remote shell.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.