Fully Detach a Process into the Background without tmux or Similar Tools
Introduces nohup (no hangup) and the & operator to move a process into the background so that it keeps running even after the terminal is closed.
Table of Contents
1. TL;DR
The combination of nohup (no hangup) and & can be used to make a task run in the background and survive after the shell is closed. Usage:
nohup [command] &
In practice, you may also want to redirect the output to a log file explicitly:
nohup [command] > output.log 2>&1 &
2. How It Works
The & operator starts the command in the background immediately, but its standard output and standard error are still printed to the current terminal. More importantly, the process still receives a SIGHUP signal and terminates when the terminal is closed.
nohup makes the process ignore SIGHUP, so it survives when the terminal closes. However, on its own the process still runs in the foreground and blocks the terminal. If the output is not already redirected, nohup also writes it to a file named nohup.out.
Combining the two keeps the process in the background and lets it survive after the terminal closes or the SSH session ends.
3. Going Further
Strictly speaking, a process started with nohup [command] & still belongs to the shell’s job table and session. If you need an even cleaner detachment:
disownremoves an already-running background job from the shell’s job table, so the shell will not forwardSIGHUPto it.setsid [command]runs the command in a brand-new session, completely separated from the current terminal.