How do I kill the last spawned background task in linux?
doSomething doAnotherThing doB & doC doD #kill doB ????
There's a special variable for this in bash:
$! expands to the PID of the last process executed in the background.
You can kill by job number. When you put a task in the background you'll see something like:
$ ./script &  35341
 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
There are a number of ways to refer to a job in the shell. The character
%introduces a job name. Job number
nmay 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,
%cerefers to a stopped
cejob. 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
cein its command line. If the substring matches more than one job, bash reports an error. The symbols
%+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.