How to manage background jobs

In the article about the tips to use the command line faster, I mentioned about bringing a command or a script to background if it takes a long time to run. In today's article, I will give some examples in details of how to manage background jobs in Linux.

How to manage background jobs in Linux

1. Make a command run in background

If you want to run a command in background, just include an ampersand ("&") at the end of the command.

2. Send a currently running command to background

If you forgot to use the ampersand to run the command in background, you dont have to kill the currently running job then start a new background job. To send a currently running command to background, you will just need to suspend the command first by hitting Ctrl + Z, after that you use the "bg" command to send the job to the background.

3. Bring the background job to foreground

If you dont want to job to run in background anymore, you can just bring it back to foreground by using the "fg" command.

4. Bring a certain background job to foreground

One problem is that, you could run multiple commands or scripts in background and the "fg" command will just bring the most recent background job to the foreground. In case multiple jobs are running in background and you want to bring a certain one to foreground, you will need to check the jobs first. The command you can use to list all the background jobs is "jobs", just run this command and you will get a list of the background jobs.

A sample output of "jobs" will be like this:
 # jobs  
 [1]  Running         bash &  
 [2]- Running         evolution &  
 [3]+ Done            nautilus .  

After that, if you want to bring the #2 job to foreground, the command you can use is:
 fg %2  

5. Kill a background job

To kill a job running in background is easy, just use any kill command with the job ID number. For example, to kill the #1 job, the command you can use is:
 kill %1  
linux tips and tricks