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.
11 min read
Explore run linux commands in background with syntax, flags, practical examples, real-world Linux administration workflows, and troubleshooting steps.
- What nohup Does and When to Use It
- Availability and Installation Across Linux Distributions
- Command Syntax, Arguments, and Exit Status Codes
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.
To run Linux commands in the background, append an ampersand (&) to the end of your command line to detach it from foreground terminal input immediately. For long-running tasks executed over remote SSH sessions, prepend nohup or use the shell disown builtin to protect the process from terminating when the terminal disconnects and receives SIGHUP (Signal Hangup).
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.
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:
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 / Flag | Long Form / Argument | Technical Behavior and Purpose |
|---|---|---|
& | Shell Operator | Appends to any command to launch it immediately as a background job. |
nohup | coreutils binary | Runs a command immune to SIGHUP signals with default I/O redirection to nohup.out. |
jobs -l | Shell Builtin | Lists all active background jobs in the current shell session along with their PIDs. |
bg %<job> | Shell Builtin | Resumes a paused or suspended (Ctrl+Z) job in the background. |
fg %<job> | Shell Builtin | Brings a background job back into the foreground interactive terminal. |
disown -h %<job> | Shell Builtin | Keeps the job in the shell jobs table but prevents SIGHUP transmission on shell exit. |
disown -a | Shell Builtin | Removes all jobs from the current shell's job table. |
2>&1 | Shell Redirection | Redirects standard error (fd 2) into standard output (fd 1) for unified logging. |
tmux new -s <name> | Multiplexer Tool | Creates 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).
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
Never launch background processes (using &) that produce verbose unredirected stdout or stderr in an active shell session. Unredirected background tasks write directly over your terminal display, corrupting text editors (nano/vim) and making it nearly impossible to type administrative commands without terminal screen corruption.
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 &
Alternatives, Related Commands, and Related Tutorials
- How to Kill a Process in Linux: kill, killall, and pkill Guide — Practical syntax, flags, and examples for
kill. - pidof Command in Linux: Find Process IDs by Program Name — Practical syntax, flags, and examples for
pidof. - ps Command in Linux: ps aux, ps -ef, Custom Columns, and Sorting — Practical syntax, flags, and examples for
ps. - pstree Command in Linux: View the Process Tree Hierarchy — Practical syntax, flags, and examples for
pstree. - 25 Best Linux Commands Every Sysadmin Should Know — Core command-line utilities for daily Linux server administration.
- How to Find a File in Linux from the Command Line — Practical file search patterns across Linux directories.
- Linux Commands Knowledge Hub (#linux-commands) — Browse all Linux command-line tutorials and system administration references.
Authoritative References and Official Documentation

The Linux Command Line, 2nd Edition: A Complete Introduction
Frequently Asked Questions
Quick answers to common questions and configurations
Editorial Disclosure: Website Vidya is supported by our readers. When you purchase hosting, tools, or software through our verified partner links, we may earn an affiliate commission at no extra cost to you. We only recommend solutions we trust and rigorously verify.
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.
Most Read Guides
TrendingUbuntu Server Not Booting? 10 Simple Steps to Fix It Fast
How to Create a 3D Button in HTML and CSS: Easy Steps
How to Install Python and Pip on Ubuntu 24.04 LTS
How to Install Nginx on Ubuntu 24.04
How to Install Python on Ubuntu 24.04 LTS
Related Technical Guides
Tested runbooks, server administration walkthroughs, and troubleshooting guides





Join the Conversation & Perspective
Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.
No comments on this guide yet. Be the first to share your thoughts or ask a question!