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.
![Daniel Porteous](https://i.stack.imgur.com/lgCDn.png?s=256&g=1)
Author by
Daniel Porteous
Updated on September 18, 2022Comments
-
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 oflsof
.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 over 7 years
lsof -p "$(pgrep myprocess)"
-
Daniel Porteous over 7 yearsThat'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 over 7 yearsisn't
xargs
created for such purpose?pgrep myprocess | xargs lsof -p
-
Admin about 6 yearslsof -p `pgrep myprocess` (one character less) :P
-
Admin about 6 yearssurrounding commands with backquotes (``) rather than with the
$()
construct would work forcsh
, and therefore fortcsh
, which is the default shell infreebsd