bash - 从 shell 脚本的输出中捕获和存储一个值,同时还显示进度?
问题描述
我使用来自上游存储库的 bash 脚本,该脚本在通过脚本时反映了高级进度。最后,它显示脚本结果的路径/文件名。我试图在不修改脚本的情况下获取该路径/文件名,因为脚本经常更改。我不知道如何获取路径/文件名。
- 如果我通过管道输出输出,
grep
那么我会丢失进度输出文本。 - 如果我使用
awk
正则表达式进行匹配,我也会丢失进度输出文本。 - 使用包装脚本,使用 , 将变量分配给命令订阅的输出
sed
失败,我不知道它是匹配、命令替换还是错误的作业工具。
我花了很多时间,想现在可能是问的好时机:
我该怎么做?
这是一个示例,仅用于演示输出。
#!/bin/bash
echo "The directory to be analyzed abc123/def456/"
echo "## CPU"
echo "## Messages"
echo "## Out of Memory"
echo "Calling other script..."
echo "Done."
echo
echo "## Please check out the file /tmp/report_user1/def456-2020-12-02.log"
输出。我正在尝试从最后一行获取路径/文件名。
The directory to be analyzed abc123/def456/
## CPU
## Messages
## Out of Memory
Calling other script...
Done.
## Please check out the file /tmp/report_user1/def456-2020-12-02.log
谢谢。
解决方案
要在终端上查看标准输出以及捕获/过滤器,一种没有 tmp 文件的方法是将任何 [实用程序或脚本]的输出tee /dev/tty
通过管道传输到 ,同时将tee
输出传输到过滤器,例如:
util | tee /dev/tty | grep '\.log$'
将上述内容捕获到 bash 变量中:
var=$(util | tee /dev/tty | grep '\.log$')
根据OP的描述,上面可以编写脚本,tee
可以通过其他方法减少输出,复制日志文件,然后执行$EDITOR ./copy.log
推荐阅读
- c# - 使用信号量调用 WaitOne 是否会释放调用线程以执行其他工作?
- ruby-on-rails - rails 模型查询返回 11 条记录但未设置限制
- asp.net-core - 从静态方法访问 HttpContext.Session
- ios - 无法添加名为 `master-1` 的 URL 为“https://github.com/CocoaPods/Specs.git”的源
- javascript - 在 iOS Safari 中同时播放两个音频文件
- java - 如何在 Android 中从多个 Json 数组中获取值,如下所示?
- php - 正则表达式花括号和引号获取内部文本
- wordpress - 如何包装 SVG 内容?
- html - 调整窗口大小时如何向下移动表格
- reactjs - React 应用程序未命中代理(package.json 文件)中描述的 url