Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there a more compact form of killing background jobs than:

for i in {1..5}; do kill %$i; done

Also, {1..5} obviously has a hard-coded magic number in it, how can I make it "N" with N being the right number, without doing a:

$(jobs | wc -l)

I actually use \j in PS1 to get the # of managed jobs, is this equivalent?

share|improve this question
3  
kill $(jobs -p) seems easier. – jw013 Jul 19 '12 at 22:00
    
I would prefer to kill jobs individually, if possible. (I might have misunderstood your comment, though) – Robottinosino Jul 19 '12 at 22:12
    
for pid in $(jobs -p); do kill $pid; done? – jw013 Jul 19 '12 at 22:27
2  
@jw013 It's not only easier, it's actually correct (please post it as an answer), unlike a solution based on counting the lines of the output of jobs which only works if the jobs happen to be numbered consecutively. Oh, and “kill jobs individually” is meaningless: passing multiple PIDs to the kill command does exactly the same thing as passing them separately. – Gilles Jul 19 '12 at 23:52
    
I was entering the command incorrectly, kill $(jobs -p) words and looks very correct to me too. Ready to accept. – Robottinosino Jul 20 '12 at 0:31
up vote 21 down vote accepted

To just kill all background jobs managed by bash, do

kill $(jobs -p)

Note that since both jobs and kill are built into bash, you shouldn't run into any errors of the Argument list too long type.

share|improve this answer
1  
Also for posterity, what bahamat thinks is the way to do it in zsh disqualifies them as any authority on the topic. – user112553 Mar 8 '13 at 23:46
    
I feel like I should know this, but how does the '$' work here? – fersarr Jan 8 '15 at 17:21
1  
@fersarr Here you go – jw013 Jan 8 '15 at 21:27
    
@bahamat That doesn't actually work since the PID may be in field 2 or 3 depending on whether the job is one of %+ or %- or not. What works is kill %${(k)^jobdirs}, which is indeed longer; if you need to list the PIDs then you can use the even longer ${${jobstates#*:*:}%%=*}. – Gilles Jan 28 at 10:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.