0
0
Bash Scriptingscripting~5 mins

Running commands in background (&) in Bash Scripting

Choose your learning style9 modes available
Introduction

Running commands in the background lets you keep using the terminal while a task runs. It helps you do many things at once without waiting.

You want to download a file but still type other commands.
You run a script that takes a long time and want to do other work meanwhile.
You start a server or service and want the terminal free for other commands.
You test a program and want to see its output later without blocking your terminal.
Syntax
Bash Scripting
command &

The ampersand (&) placed after a command runs it in the background.

You can keep typing new commands immediately after starting a background job.

Examples
This runs the sleep command in the background for 10 seconds.
Bash Scripting
sleep 10 &
This starts pinging google.com in the background so you can do other things.
Bash Scripting
ping google.com &
This runs a script named long_script.sh in the background.
Bash Scripting
./long_script.sh &
Sample Program

This script starts a sleep command in the background for 5 seconds. Then it immediately prints a message. The wait command pauses the script until the background job finishes, then prints the final message.

Bash Scripting
#!/bin/bash

echo "Start background job"
sleep 5 &
echo "This prints immediately"

wait

echo "Background job finished"
OutputSuccess
Important Notes

You can see background jobs with the jobs command.

Use fg to bring a background job to the foreground.

Background jobs still print output to the terminal unless redirected.

Summary

Use & after a command to run it in the background.

This frees your terminal to run other commands immediately.

Use wait to pause until background jobs finish if needed.