Can a shell script running in a ssh continue to run if the SSH instance closes?
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).
Related videos on Youtube
SoItBegins
Updated on September 18, 2022Comments
-
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 over 10 yearsYou can run the script within
tmux
orscreen
and reconnect later.
-
-
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 over 10 yearsThis question was asked and answered here
-
SoItBegins over 10 yearsIt certainly continued to run for me. Thank you!