Understanding the Ampersand (&) in nohup: Shell Backgrounding Explained for Developers


3 views

While nohup and the ampersand (&) are often used together, they serve fundamentally different purposes in Unix-like systems:

# Just backgrounding (will terminate when shell exits)
long_running_process &

# nohup without backgrounding (keeps running but blocks terminal)
nohup long_running_process

# Combined usage (best practice)
nohup long_running_process &

The ampersand is a shell operator that:

  • Places the command in a subshell
  • Immediately returns control to the parent shell
  • Sets the process group ID differently from foreground jobs

Backgrounding database migrations:

nohup ./run_migrations.sh > migration.log 2>&1 &

Persistent API servers:

nohup python3 api_server.py > api_output.log 2>&1 &

Output redirection: Always redirect output when using nohup with &:

# Bad practice - output goes to nohup.out by default
nohup command &

# Better practice - explicit output handling
nohup command > custom.log 2>&1 &

Modern shells offer alternatives:

# Using bash's disown after backgrounding
command &
disown -h %1

However, nohup remains more portable across different Unix environments.

Approach SIGHUP Handling Terminal Control
nohup Ignores Detaches
& alone Receives Background

The ampersand (&) symbol is actually a shell operator, not specific to nohup. It tells the shell to run the preceding command as a background process. This means:

$ nohup ./long_running_script.sh &
[1] 12345
$ nohup: ignoring input and appending output to 'nohup.out'

While nohup protects from SIGHUP (hangup signal), the ampersand makes the process run in background. They serve different but complementary purposes:

  • nohup: Makes process ignore hangup signals
  • &: Detaches process from current shell session

For server maintenance or long-running tasks, combine both:

$ nohup python3 data_processor.py > processing.log 2>&1 &

Breakdown of this command:

  1. nohup: Prevents termination when session ends
  2. > processing.log: Redirects stdout
  3. 2>&1: Redirects stderr to stdout
  4. &: Runs in background

After starting with &, you can manage the process:

# List background jobs
$ jobs

# Bring to foreground
$ fg %1

# View all processes (including background)
$ ps aux | grep data_processor

Many developers confuse these behaviors:

  • nohup without &: Process runs in foreground but survives logout
  • & without nohup: Process runs in background but terminates on logout
  • Combined: Process runs in background AND survives logout

While nohup is classic, modern alternatives exist:

# Using disown
$ ./script.sh &
$ disown -h %1

# Using screen/tmux
$ tmux new -s session_name
$ ./script.sh
# Detach with Ctrl+B, D