When you start a long-running script or a critical background process in a standard Linux terminal session, that process is tied directly to your current connection. If you accidentally close your terminal window, or if your SSH connection to a remote server drops due to network instability, Linux sends a “hangup” (SIGHUP) signal to the terminal. This signal instantly terminates every process you started in that session. To prevent this catastrophe and allow scripts to run safely in the background even after you log out, system administrators use the nohup command.
How to Use nohup for Background Processes
The word nohup literally stands for “no hangup.” By prepending it to any standard Linux command, you tell the operating system to ignore the SIGHUP signal, ensuring the process continues running uninterrupted.
To run a command with nohup and push it to the background, you use the following syntax:
nohup ./massive_database_backup.sh &
Let’s break down this syntax:
- nohup: Instructs the system to shield the process from terminal closure signals.
- ./massive_database_backup.sh: The actual script or command you want to execute.
- & (Ampersand): This symbol at the very end of the line tells the terminal to immediately push the process into the background, returning control of the command prompt to you so you can continue working.
When you press Enter, the terminal will reply with a Process ID (PID), such as [1] 45892, confirming the job is running safely.
Where Does the Output Go?
Normally, a script prints its progress and error messages directly to your screen. However, because a nohup process is designed to survive after you close the terminal, it cannot rely on a screen to display its output.
By default, nohup automatically captures everything the script prints and saves it into a text file named nohup.out, which is created in whatever directory you were in when you ran the command. You can monitor the progress of your script by checking this file:
tail -f nohup.out
Redirecting Output to a Custom File
Relying on the default nohup.out file can get messy if you are running multiple background jobs in the same directory, as they will all try to write to the same file. It is best practice to manually redirect the output to a specific, named log file.
nohup ./massive_database_backup.sh > backup_progress.log 2>&1 &
In this advanced syntax, > backup_progress.log tells Linux to save standard output to that specific file, and 2>&1 ensures that any error messages are also routed into the exact same log file, giving you a complete, permanent record of the background task.