Bash – How to combine outputs of ps and lsof

bashcommand-line-interfaceshell-scripting

Usually output of ps has a pid somewhere. Is there a way to combine this, preferably with a one-liner, with an output of lsof ?

e.g.

27915 ?        Ss     0:03 gpg-agent --daemon
gpg-agent 27915      httpd  mem     REG      104,1    144776     229236 /lib64/ld-2.5.so
gpg-agent 27915      httpd  mem     REG      104,1   1718232     229237 /lib64/libc-2.5.so
gpg-agent 27915      httpd  mem     REG      104,1     23360     229238 /lib64/libdl-2.5.so
...

6139 ?        Ss     0:00 /usr/sbin/restorecond
restoreco 6139 root  mem    REG  104,1    53880 228954 /lib64/libnss_files-2.5.so
restoreco 6139 root    0u   CHR    1,3      0t0   1771 /dev/null
...

Note: the first block's first line is output of ps for pid 27915 followed by output lsof -p 27915; the second block is same for pid 6139.

Essentially I would like a join by pid between two commands but output line(s) of first command first and then output lines of second command with same pid. The output is not the same as running something like join -1 2 -2 2 <(ps aux | sort -nk2) <(lsof | sort -nk2) — this works great but merges two outputs together on same line, producing left side repetition.

Best Answer

ps -ef | awk '{ print $1 }' | while IFS= read a_pid ; do echo "" ; ps -p $a_pid ; lsof -p $a_pid ; done