227

How do I kill the last spawned background task in Linux?

Example:

doSomething doAnotherThing doB & doC doD #kill doB ???? 
3
  • 21
    How can this be not programming related? Bash programming is not programming? Commented Oct 26, 2009 at 13:14
  • 7
    This is in the overlap region between SO and SU, but I think it fits better here on SO. My criteria for thinking this way is that if @flybywire is doing this in a script, it's programming. If he just wanted to do it from the command line I'd say it belongs on SU. Commented Oct 26, 2009 at 19:58
  • 13
    Shell scripting is programming too. Commented Oct 28, 2009 at 1:12

8 Answers 8

335

You can kill by job number. When you put a task in the background you'll see something like:

$ ./script & [1] 35341 

That [1] is the job number and can be referenced like:

$ kill %1 $ kill %% # Most recent background job 

To see a list of job numbers use the jobs command. More from man bash:

There are a number of ways to refer to a job in the shell. The character % introduces a job name. Job number n may be referred to as %n. A job may also be referred to using a prefix of the name used to start it, or using a substring that appears in its command line. For example, %ce refers to a stopped ce job. If a prefix matches more than one job, bash reports an error. Using %?ce, on the other hand, refers to any job containing the string ce in its command line. If the substring matches more than one job, bash reports an error. The symbols %% and %+ refer to the shell's notion of the current job, which is the last job stopped while it was in the foreground or started in the background. The previous job may be referenced using %-. In output pertaining to jobs (e.g., the output of the jobs command), the current job is always flagged with a +, and the previous job with a -. A single % (with no accompanying job specification) also refers to the current job.

Sign up to request clarification or add additional context in comments.

5 Comments

For the record, I think this only works if job control is enabled. Although I think you can turn it on in scripts (set -m), it's intended for interactive use. See stackoverflow.com/questions/690266/… as well
Very useful symbols, these %1 and %% - especially. Some things don't die on Ctrl-C, so you need to Ctrl-Z them, and then kill -9 %%. One example where I found it useful is: while true; do mplayer <some unstable online radio>; date >> restarts.log; done - Ctrl-C will just get you to next loop iteration. Before I had to do ps or maybe jobs -l, and then re-type the PID, which is tedious.
Is there one for all jobs?
@TomaszGandor That's why you might want to replace while true with while sleep 1. This will give you a short delay before restarts if you can live with that, and if you hit ctrl-c twice, the second one will interrupt the sleep, ending it with a non-zero exit and breaking out of the loop.
If there is confusion about which user it belongs to, the result may be "kill: failed to parse argument: '%1'" (e.g., for sudo kill %1 after Ctrl + Z in, for example, sudo less /media/someUser/364c375a-523c-41ae-b858-0fa9774540a3/grub/grub.cfg). kill %1 (without sudo) may give the desired outcome, but with an error message: "bash: kill: (23076) - Operation not permitted. and [1]+ Stopped sudo less /media/someUser/364c375a-523c-41ae-b858-0fa9774540a3/grub/grub.cfg"
255

There's a special variable for this in Bash:

kill $! 

$! expands to the PID of the last process executed in the background.

4 Comments

@polm23; no, ^Z doesn't background jobs, it stops them. A subsequent bg does the actual 'backgrounding' (resumes execution in the background), and after that $! works as expected.
Assuming the ???? stands for one or more commands to be executed after the kill, if any of those commands relies on work done by the background process, be mindful of any cleanup or finishing-up tasks which the background process might perform in a signal handler after receiving a (trappable) signal. Best to add a wait (followed perhaps by a sync or even a sleep <n>) right before the first of any such 'dependent' commands.
For completion: As a single % also refers to the current job you can kill the stopped job (^z) with "kill %". I use this almost always after ^z.
This only works if you have job-control enabled, which is only on by default in interactive shells (though since you're referring to using ctrl-z I guess you're also referring to using an interactive shell) - but this has been outlined in other answers here, not sure why this is "for completeness" :)
52

The following command gives you a list of all background processes in your session, along with the pid. You can then use it to kill the process.

jobs -l 

Example usage:

$ sleep 300 & $ jobs -l [1]+ 31139 Running sleep 300 & $ kill 31139 

Comments

32

This should kill all background processes:

jobs -p | xargs kill -9 

3 Comments

This is what I'd use before, but kill -9 %% is less typing :)
@TomaszGandor That will kill only the current job i.e. last job stopped in foreground or started in background. The command in the answer will kill ALL jobs.
2
skill doB 

skill is a version of the kill command that lets you select one or multiple processes based on a given criteria.

Comments

0

You need its pid... use "ps -A" to find it.

Comments

0

As in John Kugelman's answer, % is related to job specification.

How can we efficiently find that? Use less's &pattern command. It seems man uses the less pager (I am not that sure). In 'man' Bash, type &%, and then type Enter. It will only show lines that containing '%'. To reshow all, type &. And then Enter.

Comments

-4

Just use the killall command:

killall taskname

for more info and more advanced options, type "man killall".

2 Comments

I think killall is a bit aggressive when you actually have easy access to the PID. And dangerous, too, especially if you're root
Not very helpful, if you had to killall python or killall java, while having something useful running elswhere in the system.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.