Can a shell script running in a ssh continue to run if the SSH instance closes?

12,675

Solution 1

Yes, if you start the script to run in the background, it will continue to run. Alternately, you can start the script by using the command on command-line. For example, you can say:

ssh hostname -l loginname command

and that will work.

Solution 2

One way to do this would be to use nohup. Here is an example:

nohup your_prog.sh &

This will run the program called your_prog.sh in the background with & and redirect all the outputs to a file called nohup.out.

Now, you can monitor the output of the program running in the background by using a command like:

tail -f nohup.out

The program that is started with the nohup command will continue to run until terminated by a reboot or an explicit kill command (or until your program exits).

Share:
12,675

Related videos on Youtube

SoItBegins
Author by

SoItBegins

Updated on September 18, 2022

Comments

  • SoItBegins
    SoItBegins almost 2 years

    I'm trying to write a shell script that does a lengthy batch job on a remote server. I'll be running the script over SSH.

    The thing is, I intend to start the script in the evening and collect the results the next morning; I'd prefer not to have my local computer have to run all night, as it's not needed as part of the batch process. As such, is there a way I can close the SSH connection and still have the shell script continue to run on the remote server?

    • Admin
      Admin over 10 years
      You can run the script within tmux or screen and reconnect later.
  • goldilocks
    goldilocks over 10 years
    "Yes, if you start the script to run in the background, it will continue to run." -> Not if there's a process in there that closes automatically when it finds stdin closed. That's the major reason nohup exists, I think.
  • user52540
    user52540 over 10 years
    This question was asked and answered here
  • SoItBegins
    SoItBegins over 10 years
    It certainly continued to run for me. Thank you!