I have run a command in an ssh session and would like to keep it running even upon exit from ssh session. Is there any way to prevent termination of process upon exit from session running that process?
There are 2 ways to do this :
- nohup – To run a new process that can run in background even after closing the terminal.
- disown – Can be used when the process is already running and you have not used nohup to run it.
Lets take a simple example of a long running command like “sleep” to test both the options.
Syntax of using the nohup command is:
# nohup [command] > /tmp/command.out 2>&1
The command redirection is optional. By default, if you do not provide a output redirection the command output is saved in the same directory with file name nohup.out. For example:
# nohup sleep 4 appending output to nohup.out
You can also run the command in background along with the nohup option if you want to gain access to the terminal back. For Example:
# nohup sleep 100 &
Follow below steps if the command in question is already running without nohup:
1. Suppose you have run the command “sleep 100” without nohup as shown below:
# sleep 100
2. Hit Ctrl+Z to stop the command and get access to shell. Run bg command on shell prompt to send the command in background. Make note of job ID of command in question.
3. Prevent SIGHUP to the command in question upon exit from shell. Use the syntax below:
# disown -h [job-ID]
For example in our case we have the job ID 1, so the command would be:
# disown -h %1