Learn all the steps to run a command in background, list background processes and bring them to foregound.

Table of Contents

Run a command in background

Some commands have specific parameters to run them in background, but the global parameter to run a process in background is &. You need to add it at the end of the command.

$ wget https://example.com/file.txt &
[1] 40256
  • The output means this process has the job 1 and PID (Process ID) 40256.
  • It will show the standard output and standard error of the process in the terminal. If you don’t want this, redirect output and error to /dev/null: some_command > /dev/null 2>&1.

List background processes

Run jobs or jobs -l (-l includes the PID of the job).

$ jobs
[1]+  Running                 wget https://example.com/file.txt &

Attach to a background process

You can move a background process to foreground with fg.

fg [%<job number>]
fg %1
  • %<job number> is optional if there is only one job.

Stop/resume a process

You can stop a foreground process with Ctrl + Z. To stop a background process, you can run kill with the signal 19 (SIGSTOP):

kill -19 <process ID>
# kill -s SIGSTOP <process ID>

To resume a stopped process, use fg or use kill with the signal 18 (SIGCONT). You can specify a process ID or a job number (prepend ‘%’ to the job number):

kill -18 <process ID>
# kill -s SIGCONT <process ID>

Move a running process to background (detach)

  1. Type Ctrl + Z to stop the process.
    [1]+  Stopped                 wget https://example.com/file.txt
    • It shows the job number.
  2. Run bg with the job number.
    $ bg 1
    [1]+ wget https://example.com/file.txt

nohup: processes that keep running after closing a session

If you run a command in background using &, that command will terminate when you close the terminal window because it’s linked to it. To prevent this, there is a command called nohup (‘no hang up’). nohup blocks a SIGHUP signal from reaching a command.

nohup <command>

For example, if you run a long-running command like sleep 100:

sleep 100 &

And you close the terminal window (or terminate an SSH connection), sleep will terminate. But if you type:

nohup sleep 100 &

And you close the terminal window, sleep will keep running.

disown: bash built-in nohup alternative

disown can also block SIGHUP signals on background processes when using the -h parameter. It works with processes you have put in background and appear when jobs is executed.

disown -h %<job number>

disown can also be used to remove stopped jobs (when no parameter is used), remove all running jobs (-r), remove all jobs (-a) or remove specific jobs (typing %<job number>).