Take the 2-minute tour ×
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.

I know how to kill the last process with

 kill $!

However I would like to kill the last−1 process, i.e. not the last one, but the one before the last one.

I tried

 kill $$(($! -1))

but that didn't work.

share|improve this question
1  
$(($! - 1)) isn't the PID of the next-to-last process (why would it be?), it's the PID of the last process ($!) minus one. –  Gilles May 13 '13 at 23:07
add comment

1 Answer 1

summary:

You should use jobs to list, and use kill %n to kill the n'th backgrounded process, and if your bash supports it : kill %-1 will kill the n-1'th backgrounded process.

details:

# find / -print >/dev/null 2>/dev/null &
[1] 1291234
# find /./ -print >/dev/null 2>/dev/null &
[2] 2162424
# find /././ -print >/dev/null 2>/dev/null &
[3] 680176
#
# jobs
[1]   Running                 find / -print >/dev/null 2>/dev/null &
[2]-  Running                 find /./ -print >/dev/null 2>/dev/null &
[3]+  Running                 find /././ -print >/dev/null 2>/dev/null &
# kill %2  # or kill %-1  if your version of bath supports it
#
[2]-  Terminated              find /./ -print >/dev/null 2>/dev/null
# jobs
[1]-  Running                 find / -print >/dev/null 2>/dev/null &
[3]+  Running                 find /././ -print >/dev/null 2>/dev/null &
#

Notice the additional "enter" needed to see the [2]- Terminated find /./ -print >/dev/null 2>/dev/null message (shown only before next prompt)

Now, if your bash supports the kill %-n notation : it is easy:

kill %-1  # will kill not the n'th (or last), but the n-1'th backgrounded process

But if your bash doesn't support kill %-1 : Here is an (overly complex...) attempt at automation (which should only kill if there is a n-1th job to be killed ... hopefully)

jobs \
  | awk 'BEGIN {cur="";}

           /./ { last=cur ; cur=$0 ; }

           END { if ( last != "")
                 { print last ;} }' \
  | tr -d '[]+-' \
  | awk '{ print $1 }' \
  | xargs -I __ echo kill %__

(take out the "echo" once you're sure it does what you want it to ...)

share|improve this answer
add comment

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.