Use piped stdin as argument to next command

5,032

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.

Share:
5,032
Daniel Porteous
Author by

Daniel Porteous

Updated on September 18, 2022

Comments

  • Daniel Porteous
    Daniel Porteous almost 2 years

    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!

    • cuonglm
      cuonglm over 7 years
      lsof -p "$(pgrep myprocess)"
    • Daniel Porteous
      Daniel Porteous over 7 years
      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".
    • SparedWhisle
      SparedWhisle over 7 years
      isn't xargs created for such purpose? pgrep myprocess | xargs lsof -p
    • Admin
      Admin about 6 years
      lsof -p `pgrep myprocess` (one character less) :P
    • Admin
      Admin about 6 years
      surrounding commands with backquotes (``) rather than with the $() construct would work for csh, and therefore for tcsh, which is the default shell in freebsd