Website Vidya
Cloud & DevOpsStep-by-Step Guide

How to Run Linux Commands in the Background: &, nohup, disown

Explore run linux commands in background with syntax, flags, practical examples, real-world Linux administration workflows, and troubleshooting steps.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
How to Run Linux Commands in the Background: &, nohup, disown
AI Executive SummaryWebsiteVidya AI

11 min read

Explore run linux commands in background with syntax, flags, practical examples, real-world Linux administration workflows, and troubleshooting steps.

Key Highlights
  • What nohup Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Knowing how to run linux commands in background execution is a fundamental operational skill for every system administrator, developer, and data engineer. By default, interactive Unix shells execute commands synchronously in the foreground, blocking your command prompt, intercepting keyboard input, and tying process survival directly to the lifetime of the active terminal session or SSH connection.

When running long-running operations—such as multi-gigabyte database dumps, recursive filesystem backups, software compilation pipelines, or batch data processing scripts—losing your network connection or accidentally closing a terminal emulator can terminate hours of work in an instant. Linux provides a versatile hierarchy of mechanisms to decouple processes from foreground interactive shells: the simple shell ampersand (&) operator, POSIX job control commands (jobs, bg, fg), the immune execution wrapper nohup, the shell disown builtin, and full terminal multiplexers like tmux.

Understanding how these mechanisms interact with process groups, controlling terminals, standard I/O streams, and Unix signals (specifically SIGHUP) ensures your mission-critical jobs continue running smoothly and deterministically without human supervision.

Advertisement
How to Run Linux Commands in the Background: &, nohup, disown — syntax, flags, and practical terminal workflow diagram
How to Run Linux Commands in the Background: &, nohup, disown — command syntax, key options, and production workflow reference.

What nohup Does and When to Use It

At the kernel and shell architecture level, background execution revolves around POSIX Job Control and Session Management. When you execute a standard foreground command, the shell places the process into its own foreground Process Group ID (PGID) and yields control of the terminal device (/dev/tty). The terminal driver directs keyboard interrupts (such as Ctrl+C for SIGINT and Ctrl+Z for SIGTSTP) exclusively to this foreground process group.

When you append an ampersand (&), the shell creates the child process in a background process group. The background process retains open file descriptors inherited from the parent shell for standard output (stdout) and standard error (stderr), but any attempt to read from standard input (stdin) causes the kernel to suspend the process with SIGTTIN. Furthermore, when an SSH session disconnects or a terminal window is closed, the kernel sends a SIGHUP (Signal 1 - Hangup) to the session leader (the login shell). By default, the shell propagates SIGHUP to all child process groups in its job table, terminating them immediately unless they have explicitly masked SIGHUP using nohup, detached from the job table with disown, or isolated inside a daemon supervisor.

Under the hood, nohup gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as &, nohup, jobs -l, bg %<job> turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The nohup utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether nohup is installed and inspect which binary path and version your shell resolves:

type -a nohup
nohup --version 2>/dev/null || man -f nohup

# Illustrative output (reviewed against documentation)
nohup is /usr/bin/nohup
nohup (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

COMMAND & | nohup COMMAND [ARGS] > OUT.log 2>&1 & | disown -h %JOBID

Linux provides multiple complementary syntaxes depending on your objective: COMMAND & launches an immediate background job while returning the shell prompt; nohup COMMAND [ARGS] > FILE.log 2>&1 & runs the command immune to hangups with redirected streams; and disown -h %JOBID strips a currently running background job from the shell's SIGHUP dispatch list.

When managing active shell jobs, POSIX builtins provide precise control: pressing Ctrl+Z sends SIGTSTP to suspend the active foreground command; jobs -l lists active background jobs and their PIDs; bg %N instructs suspended job N to resume execution in the background; and fg %N brings background job N back into foreground interactive control.

  • 0 — Successful background invocation or job control command completion.
  • 1 — Operational failure, such as referencing an invalid job ID (%N) or invalid redirection path.
  • 126 — The command specified with nohup was found but could not be invoked (e.g. permission denied).
  • 127 — The command specified with nohup was not found in PATH or the binary does not exist.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
&Shell OperatorAppends to any command to launch it immediately as a background job.
nohupcoreutils binaryRuns a command immune to SIGHUP signals with default I/O redirection to nohup.out.
jobs -lShell BuiltinLists all active background jobs in the current shell session along with their PIDs.
bg %<job>Shell BuiltinResumes a paused or suspended (Ctrl+Z) job in the background.
fg %<job>Shell BuiltinBrings a background job back into the foreground interactive terminal.
disown -h %<job>Shell BuiltinKeeps the job in the shell jobs table but prevents SIGHUP transmission on shell exit.
disown -aShell BuiltinRemoves all jobs from the current shell's job table.
2>&1Shell RedirectionRedirects standard error (fd 2) into standard output (fd 1) for unified logging.
tmux new -s <name>Multiplexer ToolCreates a persistent terminal session detached from physical SSH connections.

Choosing between a raw ampersand (&), nohup, and disown depends entirely on whether you need the process to survive terminal disconnection. A command launched with simple & will terminate the moment you close your SSH session unless the shell option huponexit is disabled (Bash defaults to off, but many distros enable it).

Advertisement

Using nohup is best suited for non-interactive batch scripts where you want guaranteed immunity to SIGHUP before launching. However, if you have already started a long-running process in the foreground without nohup, you can smoothly transition it without restarting: press Ctrl+Z to suspend, type bg to resume in the background, and execute disown -h to make it immune to terminal closure.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Launch a Long-Running Task in the Background with Ampersand

Append & to run a file compression or backup task in the background while keeping your shell prompt interactive.

tar -czf site_backup.tar.gz /var/www/html &
echo "Shell is ready for next command: PID of background job is $!"

# Illustrative output (reviewed against documentation)
[1] 14820
Shell is ready for next command: PID of background job is 14820

The shell returns job number [1] and Process ID 14820, instantly releasing the command prompt for continued work.

2. Run a Process Immune to SIGHUP with Explicit Stream Redirection

Use nohup combined with stdout and stderr redirection so the process survives SSH logout and writes logs to a dedicated file.

nohup python3 -u process_data.py > data_import.log 2>&1 &
echo "Job started in background under nohup."

# Illustrative output (reviewed against documentation)
[2] 15104
Job started in background under nohup.

nohup masks SIGHUP, > data_import.log redirects stdout, 2>&1 redirects stderr, and & detaches it into the background.

3. List and Inspect Active Shell Background Jobs

Use the jobs -l command to view active background tasks, their status (Running/Stopped), and their respective PIDs.

jobs -l

# Illustrative output (reviewed against documentation)
[1]- 14820 Running                 tar -czf site_backup.tar.gz /var/www/html &
[2]+ 15104 Running                 nohup python3 -u process_data.py > data_import.log 2>&1 &

jobs -l lists the job numbers ([1], [2]), whether it is the default job (+ or -), the process PID, and current state.

4. Suspend a Foreground Task and Resume It in the Background

If a foreground task is taking longer than expected, pause it with Ctrl+Z and send it to the background using bg.

# Press Ctrl+Z while command is running:
# ^Z
# [3]+  Stopped                 rsync -avz /data/ /backup/data/
bg %3
jobs -l

# Illustrative output (reviewed against documentation)
[3]+ rsync -avz /data/ /backup/data/ &
[3]+ 15892 Running                 rsync -avz /data/ /backup/data/ &

Ctrl+Z sends SIGTSTP to pause execution, and bg %3 delivers SIGCONT to resume the job in the background.

5. Disown an Existing Background Process to Survive Logout

Protect an active background job from closing when your SSH terminal terminates using the disown -h command.

disown -h %3
# Now safe to exit shell:
exit

# Illustrative output (reviewed against documentation)
# Job %3 remains running in background after SSH disconnects.

The -h flag sets the hangup ignore flag on the job, preventing the shell from sending SIGHUP when the user logs out.

6. Bring a Background Task Back into the Foreground

Use fg %N to bring a background job back into the foreground when you need to inspect interactive prompts or provide input.

fg %1

# Illustrative output (reviewed against documentation)
tar -czf site_backup.tar.gz /var/www/html
# Interactive control restored to terminal

fg moves job 1 back into the foreground process group and reattaches the terminal keyboard input.

Real-World Workflows, Pipelines, and Shell Automation

Long-Running Database Backup and Compression Resilient to SSH Dropouts

Execute a mission-critical multi-gigabyte database export and compression pipeline that guarantees survival through network disconnects.

#!/usr/bin/env bash
set -euo pipefail

BACKUP_DIR="/opt/backups"
LOG_FILE="${BACKUP_DIR}/db_dump_$(date +%Y%m%d_%H%M%S).log"
mkdir -p "${BACKUP_DIR}"

echo "Launching resilient database backup in background..."
nohup bash -c '
  set -euo pipefail
  echo "[$(date)] Starting pg_dump..."
  pg_dump -U postgres -d production_db | gzip -9 > /opt/backups/prod_db_$(date +%Y%m%d).sql.gz
  echo "[$(date)] Database backup completed successfully."
' > "${LOG_FILE}" 2>&1 &

BACKUP_PID=$!
echo "Backup process spawned under PID ${BACKUP_PID}."
echo "Logs streaming to ${LOG_FILE}. Safe to disconnect SSH."

# Illustrative output (reviewed against documentation)
Launching resilient database backup in background...
Backup process spawned under PID 19204.
Logs streaming to /opt/backups/db_dump_20261022_194510.log. Safe to disconnect SSH.

Encapsulating the pipeline inside nohup bash -c '...' guarantees that pipes, redirections, and subshells survive terminal disconnects.

Converting an Accidentally Foregrounded Task to a Disowned Daemon

Safely convert an accidental foreground command into an independent background process without interrupting work.

# 1. Press Ctrl+Z to freeze the running command
# ^Z
# [1]+ Stopped  ./long_running_migration.sh

# 2. Resume execution in background
bg %1

# 3. Disown from current shell
disown -h %1

# 4. Verify process is active and verify its PID via ps
PID=$(jobs -p %1)
echo "Process ${PID} is now immune to SIGHUP."
ps -o pid,stat,time,comm -p "${PID}"

# Illustrative output (reviewed against documentation)
[1]+ ./long_running_migration.sh &
Process 21402 is now immune to SIGHUP.
    PID STAT     TIME COMMAND
  21402 S        0:14 long_running_migration.sh

The Ctrl+Z -> bg -> disown sequence is the ultimate emergency recovery pattern for sysadmins who forget to use nohup or tmux.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding nohup inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Background processes retain the exact security context, user credentials (UID/GID), and Linux capabilities of the shell that spawned them. However, on systemd-based Linux systems, the setting KillUserProcesses=yes in /etc/systemd/logind.conf may cause systemd-logind to terminate all user processes when the user's last session closes, regardless of nohup or disown. To guarantee persistence across logouts for regular users, administrators should configure loginctl enable-linger <username> or deploy tasks as proper systemd services.

When running background commands that accept credentials, avoid passing sensitive API keys or database passwords directly as CLI arguments (e.g. mysql -pSecret &). Arguments of background processes remain visible to all local users via /proc/[pid]/cmdline and utilities like ps aux throughout the lifetime of the process.

GNU/Linux, BSD, and BusyBox Implementation Differences

The ampersand operator & and job control commands (jobs, fg, bg) are standardized by POSIX and function identically across Bash, Dash, KornShell (ksh), Zsh, and BusyBox shells.

However, disown is a shell builtin specific to Bash, Zsh, and Ksh; it is not defined in standard POSIX /bin/sh or Dash (the default non-interactive shell on Debian and Ubuntu). When writing portable scripts, prefer using nohup COMMAND > log 2>&1 & rather than relying on disown.

Troubleshooting Common Errors and Diagnostics

Background command terminated immediately after closing SSH connection

Root Cause: The command was launched with simple & without masking SIGHUP, or systemd-logind KillUserProcesses=yes killed lingering session processes.

Resolution: Use nohup or tmux, and enable linger for the user account with loginctl enable-linger <user>.

nohup ./script.sh > script.log 2>&1 &
# Or enable systemd user lingering:
loginctl enable-linger $USER

Cannot see background jobs after opening a new SSH session

Root Cause: The jobs command only lists jobs tied to the current shell subshell; a new SSH session creates a separate shell with an empty job table.

Resolution: Use ps, pgrep, or top to locate the process by name or PID.

pgrep -fl script.sh
ps aux | grep script.sh

nohup: ignoring input and appending output to 'nohup.out' permission denied

Root Cause: nohup was executed in a directory where the user lacks write permissions, and no output redirection (> file.log) was specified.

Resolution: Explicitly redirect stdout and stderr to a writable directory such as /tmp or the user's home directory.

nohup ./script.sh > /tmp/script.log 2>&1 &

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The ampersand (&) detaches the command to run in the background within the current shell session, but it will still terminate if the shell receives SIGHUP upon logout. nohup explicitly masks SIGHUP, allowing the background process to continue running even after you log out of SSH.
2>&1 redirects standard error (file descriptor 2) to the same destination as standard output (file descriptor 1). This ensures that both regular program messages and error warnings are captured in the specified log file.
If you are in the same terminal session, type 'jobs -l'. If you have logged out and reconnected, use 'ps aux | grep <command_name>' or 'pgrep -fl <command_name>' to verify the process.
While nohup works well for unattended non-interactive scripts, tmux creates an interactive persistent terminal session. With tmux, you can disconnect from SSH, reconnect hours later from a different computer, reattach to the session, and see the exact terminal screen and interactive output.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Cloud & DevOps•

How to Close File Descriptors Above 9 in Dash Shell

Attempting to close a file descriptor above 9 in Dash using exec 10<&- results in a 10: not found error because Dash's POSIX lexer only recognizes single-digit file descriptors (0–9) in redirection operators. This guide explains the exact parser limitation, why FDs 10+ are reserved for internal shell state, and how to safely close inherited file descriptors using close_range, Python, or Perl wrappers.

RR
Rajesh Rai
Read More
Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout