How to run a command in the background in Bash
Run commands in the background in Bash with &, track their PID with $!, wait for completion with wait, and keep them alive after logout with nohup or disown.
Tldr
Append `&` to run a command in the background and get your prompt back immediately. Capture its PID with `$!`, wait for it (and get its exit status) with `wait "$pid"`, and use `nohup command &` or `disown` if the command must survive terminal/session closure.
Intro
Backgrounding lets a script or shell continue working while a long-running task executes separately. This guide covers launching, tracking, waiting on, and detaching background jobs.
Steps
Name
Launch a command in the background
Text
The & operator returns control to the shell immediately; Bash prints the job number and PID.
Name
Capture the PID for later use
Text
$! always holds the PID of the most recently backgrounded job, useful for checking status or killing it later.
Name
Wait for a background job and get its exit code
Text
wait blocks until the given PID (or all background jobs if called with no arguments) finishes, and returns that job's exit status as its own.
Name
Run multiple jobs in parallel and wait for all
Text
Launch several background jobs, collect their PIDs, then wait for each in a loop to know exactly which ones failed.
Name
Keep a job running after the shell exits
Text
A backgrounded job normally receives SIGHUP when its parent shell/terminal closes. nohup ignores SIGHUP; disown removes the job from the shell's job table so it is not tracked (and not hung up) at shell exit.
Faq
Q
What is the difference between & and nohup command &?
A
& alone just runs the command asynchronously within the current session — closing the terminal typically sends SIGHUP and kills it. nohup additionally makes the process ignore SIGHUP, so it keeps running after you log out.
Q
How do I bring a background job back to the foreground?
A
Use `fg %1` (or just `fg` for the most recent job) to bring job number 1 back into the foreground; use `jobs` first to list running background jobs and their numbers.
Q
Can I check if a background process is still running without wait?
A
Yes: `kill -0 "$pid" 2>/dev/null` returns success if the process still exists (without actually sending a signal), which is a non-blocking way to poll status.