0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Run a Command in Background in Bash Shell

To run a command in the background in Bash, add & at the end of the command. This lets the shell start the command and immediately return control to you while the command runs behind the scenes.
📐

Syntax

Use the & symbol at the end of your command to run it in the background. This tells Bash to start the command and not wait for it to finish before giving you back the prompt.

  • command: The command you want to run.
  • &: Runs the command in the background.
bash
command &
💻

Example

This example runs a simple sleep command in the background. You will see the shell prompt immediately after starting it, while the command runs silently.

bash
sleep 5 &
echo "This prints immediately after starting sleep"
Output
[1] 12345 This prints immediately after starting sleep
⚠️

Common Pitfalls

One common mistake is forgetting the &, which makes the shell wait for the command to finish before returning the prompt. Another is not handling output, which can clutter your terminal if the background command prints messages.

Also, if you close the terminal, background jobs may stop unless you use tools like nohup or disown.

bash
wrong way:

sleep 5
echo "This prints after sleep finishes"

right way:

sleep 5 &
echo "This prints immediately"
📊

Quick Reference

CommandDescription
command &Run command in background
jobsList background jobs
fg %1Bring job 1 to foreground
bg %1Resume stopped job 1 in background
nohup command &Run command immune to hangups

Key Takeaways

Add & at the end of a command to run it in the background in Bash.
Background commands let you keep using the shell without waiting.
Use jobs, fg, and bg to manage background tasks.
Remember background jobs may stop if the terminal closes unless protected.
Redirect output or use nohup to avoid terminal clutter or job termination.