5

How do I use the output of a command as a parameter in another command? My specific example is that I want to get the PID of a process using pgrep and pass it to the -p option of lsof.

I've tried things like the following:

  • pgrep myprocess | lsof -p /dev/stdin
  • pgrep myprocess | lsof -p -

I know you can do it like this:

pid=$(pgrep myprocess) && lsof -p "$pid"

But there has to be a better way to do it. Perhaps xargs or something? I haven't been able to find something clean, so I'd appreciate any help.

Thanks!

  • 5
    lsof -p "$(pgrep myprocess)" – cuonglm Nov 28 '16 at 5:33
  • That's pretty good, but just wondering if there is a way which preserves the order of operations as you would imagine they should flow. Consider "we get the pid of the process, then use it in lsof". – Daniel Porteous Nov 28 '16 at 5:42
  • 1
    isn't xargs created for such purpose? pgrep myprocess | xargs lsof -p – David Dai Nov 28 '16 at 5:51
  • lsof -p `pgrep myprocess` (one character less) :P – user86041 May 22 '18 at 17:20
  • surrounding commands with backquotes (``) rather than with the $() construct would work for csh, and therefore for tcsh, which is the default shell in freebsd – user86041 May 22 '18 at 17:22
4

Assuming that pgrep may return multiple PIDs:

$ pgrep mycommand | xargs -n 1 lsof -p

This will, for each PID, run lsof -p with the PID appended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.