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.


  • 5
    lsof -p "$(pgrep myprocess)"
    – cuonglm
    Nov 28, 2016 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". Nov 28, 2016 at 5:42
  • 1
    isn't xargs created for such purpose? pgrep myprocess | xargs lsof -p Nov 28, 2016 at 5:51
  • lsof -p `pgrep myprocess` (one character less) :P
    – user86041
    May 22, 2018 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, 2018 at 17:22

1 Answer 1


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.

You must log in to answer this question.

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