Shell – Use piped stdin as argument to next command

argumentscommand lineshell

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!

Best Answer

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.