Macos 如何从上一个命令';s输出

Macos 如何从上一个命令';s输出,macos,terminal,Macos,Terminal,我对终端脚本世界非常陌生。以下是我想做的: 1) Find out the process that's using a given port (8000 in this case) 2) Kill that process 很简单。我可以使用以下工具手动执行此操作: lsof -i tcp:8000 -- get the PID of what's using the port kill -9 $PID -- terminate the app using the port 以下是使用ls

我对终端脚本世界非常陌生。以下是我想做的:

1) Find out the process that's using a given port (8000 in this case)
2) Kill that process
很简单。我可以使用以下工具手动执行此操作:

lsof -i tcp:8000 -- get the PID of what's using the port
kill -9 $PID -- terminate the app using the port
以下是使用lsof-i tcp:8000时返回的内容,仅供参考

COMMAND   PID       USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
php     94735     MyUser    5u  IPv6 0x9fbd127eb623aacf      0t0  TCP localhost:irdmi (LISTEN)

这是我的问题:如何从
lsof-I tcp:8000
捕获PID值,以便在下一个命令中使用该变量?
我知道如何创建分配的变量。。。只是不是动态制作的。

以下几点应该可以:

lsof -i tcp:8000 | grep TCP | read cmd pid restofline
kill -9 $pid

在使用kill命令之前,只需回显它以确保

你要找的东西叫做。它允许您将命令的输出视为shell的输入

例如:

$ mydate="$(date)"
$ echo "${mydate}"
Mon 24 Feb 2014 22:45:24 MST
也可以使用
`backticks`
代替美元符号和圆括号,但大多数人建议避免这样做

在您的情况下,您可能希望执行以下操作:

$ PID="$(lsof -i tcp:8000 | grep TCP | awk '{print $2}')"
$ kill $PID

类似于
(read cmd pid restofline&&kill-9$pid)
可能更好,这样管道子shell中设置的
$pid
变量就不会在转到下一个命令时丢失。工作非常好,您已经链接到了一个好的资源!非常感谢。链接已被删除:(