Choose a solution
To keep a command running after your SSH session closes, choose one of the following solutions:
Solution 1: Use the nohup and & commands: Best for running one-time, non-interactive automated scripts or commands.
Solution 2: Use GNU screen: Best for long-running, interactive tasks that may require debugging or be resumed later.
Solution 1: Use the nohup and & commands
The nohup command lets a process continue running after you close the terminal, and the & symbol sends the process to the background.
Run the command in the background.
This command redirects both output and error to
[your_log_file].sudo nohup [your_command] >[your_log_file] 2>&1 &For example, to run
bash hello.shin the background and write the output to a new file namedoutput.login the current directory, run the following command:sudo nohup bash hello.sh > output.log 2>&1 &.View the command output.
sudo tail -f [your_log_file]End the process.
ImportantTerminating the process ends the command or task. Proceed with caution.
Find the Process ID (PID). Replace
[your_command]with the command you ran in Step 1.sudo ps aux | grep "[your_command]"For example, if you ran
sudo nohup bash hello.sh > output.log 2>&1 &, you would runsudo ps aux | grep "bash hello.sh"to find its PID.Use the
sudo kill [PID]command to terminate the process.
Solution 2: Use GNU screen
Install GNU screen.
For Alibaba Cloud Linux and CentOS
sudo yum install -y screenFor Debian and Ubuntu
sudo apt-get install -y screen
Create and enter a new session.
[Name]is a custom name for your session.screen -S [Name]For example, to create a session named
mysession, runsudo screen -S mysession.Run your task in the new session.
Detach the session.
Press
Ctrl+A+Dto detach the currentscreensession.Resume the session.
List the available screen sessions to find the target session's PID.
sudo screen -lsThere is a screen on: 2046.mytask (Detached) 1 Socket in /run/screen/S-root.In this example, the session PID is
2046.Resume the session.
Replace
[PID]with the session PID from the previous step.sudo screen -r -d [PID]For example, to resume the session with a PID of 2046, run
sudo screen -r -d 2046.
Terminate the session.
ImportantTerminating a session also ends all tasks and commands running within it. Proceed with caution
Replace
[PID]with session's PID.sudo kill [PID]