3

The shell command jobs supports a -p option to just get the list of process ids. Is there an easy way to get just a list of job ids? (I know there is, but I am not really a shell guy (yet)).

This would be very handy for kill, as killing a job id instead of a process id seems to also kill all child processes.

0

2 Answers 2

4

You can do something like this:

# create some background jobs
sleep 10 & sleep 10 & sleep 10 & sleep 10 & 
jobs | awk -F '[][]' '{print "%" $2}'

This will return

%1
%2
%3
%4

which I assume is what you're after.

4

This would be very handy for kill, as killing a job id instead of a process id seems to also kill all child processes.

You can do this a different way.

When it prints the pid, you can kill it and all its children by killing its process group.

You do this by negating the pid, e.g.

$ cat &
[1] 21273
$ kill -- -21273

You need to write -- or else -pid is interpreted as a signal (e.g. like kill -9).

Example:

$ man ls &
[1] 22267

$ ps j | head -1; ps j | grep 22267
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
18968 22267 22267 18968 pts/2    22327 T      500   0:00 man ls
22267 22281 22267 18968 pts/2    22327 T      500   0:00 /bin/sh /usr/bin/nroff -mandoc -Tutf8
22267 22282 22267 18968 pts/2    22327 T      500   0:00 less
22281 22286 22267 18968 pts/2    22327 T      500   0:00 groff -mtty-char -Tutf8 -mandoc
22286 22287 22267 18968 pts/2    22327 T      500   0:00 troff -mtty-char -mandoc -Tutf8
22286 22288 22267 18968 pts/2    22327 T      500   0:00 grotty

$ kill -- -22267
[1]+  Terminated              man ls

$ ps j | grep 22267

$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .