如何从上一个命令的输出中分配终端变量

Jac*_*anz 3 macos terminal

我对终端脚本世界非常陌生.这就是我想要做的事情:

1) Find out the process that's using a given port (8000 in this case)
2) Kill that process
Run Code Online (Sandbox Code Playgroud)

很简单.我可以手动使用:

lsof -i tcp:8000 -- get the PID of what's using the port
kill -9 $PID -- terminate the app using the port
Run Code Online (Sandbox Code Playgroud)

作为参考,这里正是使用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)
Run Code Online (Sandbox Code Playgroud)

这是我的问题:如何捕获PID值,lsof -i tcp:8000以便我可以将该变量用于下一个命令? 我知道如何创建我指定的变量...而不是动态制作的变量.

and*_*otn 14

您正在寻找的东西称为命令替换.它允许您将命令的输出视为shell的输入.

例如:

$ mydate="$(date)"
$ echo "${mydate}"
Mon 24 Feb 2014 22:45:24 MST
Run Code Online (Sandbox Code Playgroud)

也可以使用`backticks`而不是美元符号和括号,但大多数shell样式指南建议避免使用它.

在你的情况下,你可能想要做这样的事情:

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