How to kill the (last - 1) PID with bash

13,046

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:
13,046

Related videos on Youtube

musicisme
Author by

musicisme

Updated on September 18, 2022

Comments

  • musicisme
    musicisme over 1 year

    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.

    • Gilles 'SO- stop being evil'
      Gilles 'SO- stop being evil' almost 11 years
      $(($! - 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.