code_fodder
code_fodder

Reputation: 16331

How to list all background pids in bash

Either I am not able to phrase my search correctly or the answer is not easy to find!, but I am trying to figure out how to list all of my background task PIDs. For example:

So far I have found that to list the last PID we use:

$!

But now I want to list the PID of the task before that (if one exists), but I can't find how to do that. Utlimatly I want to list all my background task PIDs.

I know we can also find last job ID with:

%% (last job in list)
%1 (first job in list)
%2 (second job in list)

But the same does not seem to work for process id?

Thanks all :)

Upvotes: 21

Views: 37099

Answers (4)

Michael Kazarian
Michael Kazarian

Reputation: 4462

Use ps S. For example:

$ vim &
[1] 8263
$ ipython &
[2] 8264
$ ps S
 PID TTY      STAT   TIME COMMAND
 3082 pts/0    Ss     0:00 bash
 3137 pts/0    Sl+    0:00 python /usr/bin/ipython
 8207 pts/2    Ss     0:00 bash
 8263 pts/2    T      0:00 vim
 8264 pts/2    Tl     0:00 python /usr/bin/ipython
 8284 pts/2    Tl     0:00 python /usr/bin/ipython
 8355 pts/2    R+     0:00 ps S

If you want get PIDs use below:

$ ps S | awk '{print  $  1 }' | grep -E '[0-9]'
3082
3137
8207
8263
8264
8284
8357
8358
835

Also you can use jobs -l But it show background processes only for current session.

Upvotes: 33

Alfe
Alfe

Reputation: 59426

If you also want to see your child processes which aren't handled as a job by the shell anymore (e. g. because you disowned them deliberately or similar), then you can use this to find all processes which have you as their parent:

grep "PPid:.*$$" /proc/[0-9]*/status | cut -d/ -f3

Also

ps --ppid $$

can be of use. (Credits to @Michael Kazarian who also has an answer here.)

Upvotes: 1

ghoti
ghoti

Reputation: 46846

In bash, as in tcsh, the command you probably want is jobs -l (for Long).

[ghoti@pc ~]$ sleep 300 &
[1] 33811
[ghoti@pc ~]$ sleep 301 &
[2] 33812
[ghoti@pc ~]$ sleep 302 &
[3] 33813
[ghoti@pc ~]$ jobs -l
[1]- 33811 Running                 sleep 300 &
[2]- 33812 Running                 sleep 301 &
[3]+ 33813 Running                 sleep 302 &
[ghoti@pc ~]$ 

Upvotes: 5

cnicutar
cnicutar

Reputation: 182629

But the same does not seem to work for process id?

You can try jobs -l or -p. The -l and -p switches cause the jobs command to also output process IDs.

Upvotes: 16

Related Questions