如何在后台运行命令并捕获输出
在脚本中间,我有一个使用 ssh -R 80:localhost:8080 localhost.run 公开本地端口的命令,我需要在后台执行此命令,解析输出并保存它变成一个变量。
输出返回:
Welcome to localhost.run!
...
abc.lhrtunnel.link tunneled with tls termination, https://abc.lhrtunnel.link
需要捕获这部分:
https://abc.lhrtunnel.link
结果如下:
...
hostname=$(command)
echo $hostname
...
In the middle of the script, I have a command that exposes the local port with ssh -R 80:localhost:8080 localhost.run
I need to execute this command in the background, parse the output and save it into a variable.
The output returns:
Welcome to localhost.run!
...
abc.lhrtunnel.link tunneled with tls termination, https://abc.lhrtunnel.link
Need to capture this part:
https://abc.lhrtunnel.link
As a result something like this:
...
hostname=$(command)
echo $hostname
...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这个 Shellcheck - 干净的代码:
sed
的-n
选项意味着除非明确指示打印,否则它不会打印输入中的行。s/^.*通过 tls 终止进行隧道传输,//p
适用于包含任何内容的输入行,后跟字符串通过 tls 终止进行隧道传输,
。它会删除该行中直到该字符串末尾的所有内容并打印结果,希望该结果是您想要的 URL。declare -p varname
是一种比使用echo
更可靠、更有用的显示变量值的方法。Try this Shellcheck-clean code:
-n
option tosed
means that it doesn't print lines from the input unless explicitly instructed to print.s/^.*tunneled with tls termination, //p
works on input lines that contain anything followed by the stringtunneled with tls termination,
. It deletes everything on the line up to the end of that string and prints the result, which hopefully will be the URL that you want.declare -p varname
is a much more reliable and useful way to show the value of a variable than usingecho
.