Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What's the difference between nohup and ampersand (&) on Linux?
nohup and the ampersand (&) are both used to run processes in the background on Linux, but they serve different purposes and behave differently when the terminal session ends.
The Ampersand (&) Operator
The & operator runs a command in the background, allowing you to continue using the terminal while the process executes. However, the process is still attached to the terminal session.
command &
Example
sleep 100 &
[1] 12345
The output shows the job number [1] and process ID 12345. The process runs in the background, but if you close the terminal, the process will be terminated.
The nohup Command
nohup (no hang up) runs a command that ignores the HUP (hang up) signal. This means the process continues running even after the terminal session is closed. By default, nohup redirects output to a file called nohup.out.
nohup command
Example
nohup sleep 100
nohup: ignoring input and appending output to 'nohup.out'
Combining nohup and &
For maximum effectiveness, combine both nohup and & to run a process in the background that survives terminal closure:
nohup command &
Example
nohup python script.py &
[1] 12346 nohup: ignoring input and appending output to 'nohup.out'
Key Differences
| Feature | & (Ampersand) | nohup |
|---|---|---|
| Background execution | Yes | No (runs in foreground) |
| Survives terminal closure | No | Yes |
| Ignores HUP signal | No | Yes |
| Output redirection | Normal | To nohup.out by default |
| Job control | Available (fg, bg, jobs) | Not available |
Common Use Cases
Use & alone when you want to run a quick background task but don't mind if it stops when you close the terminal.
Use nohup when you need a process to continue running after logging out, such as long-running scripts or server processes.
Use nohup & for the best of both worlds − background execution that survives terminal closure.
Managing Background Processes
You can monitor and control background processes using these commands:
jobs # List active jobs fg %1 # Bring job 1 to foreground bg %1 # Resume job 1 in background kill %1 # Kill job 1 ps aux # List all running processes
Conclusion
The ampersand (&) runs commands in the background but terminates them when the terminal closes, while nohup ensures processes survive terminal closure. For persistent background processes, combining both (nohup command &) provides the most reliable solution.
