How to Use & in Bash: Run Commands in Background
In bash, placing
& at the end of a command runs it in the background, allowing the shell to accept new commands immediately. This is useful for running long tasks without waiting for them to finish.Syntax
The basic syntax to run a command in the background is:
command &Here:
commandis any bash command or script you want to run.&tells bash to run the command in the background.
bash
sleep 10 &Output
[1] 12345
Example
This example shows running a sleep command in the background, so the shell is free to accept new commands immediately.
bash
echo "Start" sleep 5 & echo "This runs immediately after starting sleep" wait
Output
Start
This runs immediately after starting sleep
Common Pitfalls
One common mistake is forgetting the &, which causes the shell to wait for the command to finish before accepting new input. Another is running background commands that produce output without redirecting it, which can clutter the terminal.
Example of wrong and right usage:
bash
# Wrong: runs in foreground sleep 5 echo "Done" # Right: runs in background sleep 5 & echo "Done"
Output
Done
Quick Reference
Tips for using & in bash:
- Use
&to run commands without blocking the shell. - Use
jobsto list background jobs. - Use
fgto bring a background job to the foreground. - Redirect output of background jobs to avoid terminal clutter.
Key Takeaways
Add
& after a command to run it in the background in bash.Background commands let you keep using the shell without waiting.
Use
jobs and fg to manage background tasks.Redirect output of background commands to keep your terminal clean.
Forgetting
& runs commands in the foreground, blocking the shell.