The single ampersand &
is used to run commands asynchronously in the background.
From the bash docs:
If a command is terminated by the control operator ‘&’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the background, and these are referred to as asynchronous commands. The shell does not wait for the command to finish, and the return status is
0
(true).
Bash &
can be very useful, but it does come with a small catch—you have to remember to kill the task.
Let’s do an example.
Running a background task
At my day job, we occasionally need to connect directly to services in staging (or production in an emergency). It’s a two-step process, but for ease-of-use we do it in a single command, so it requires a background task. Here’s how it works:
- Start a proxy in the background with
&
- Use the proxy to connect directly to a staging/production database
Here’s a pared down version of the shell command:
# start the proxy
cloud_sql_proxy -instances=more:info:here &
# connect to postgres via the proxy
psql -h 127.0.0.1 -p 1337 -U username -d database_name
As written above, this command has a subtle bug; we have to remember to kill the background task. The cloud_sql_proxy
was run in the background via &
, which means that when we exit the postgres shell via exit
or ctrl c
, the proxy won’t stop. In this case, the proxy task is pretty light weight, so it doesn’t matter too much, but it can cause issues or just be confusing later on.
There are many ways to kill processes, and you’ll often see &
used in combination with the trap
command for that purpose.
Helpful Links
- How to kill a running process – me!
- The Bash trap command – also me!
- Lists of commands – Bash docs