首页 > 解决方案 > 从 shell 脚本的输出中捕获和存储一个值,同时还显示进度?

问题描述

我使用来自上游存储库的 bash 脚本,该脚本在通过脚本时反映了高级进度。最后,它显示脚本结果的路径/文件名。我试图在不修改脚本的情况下获取该路径/文件名,因为脚本经常更改。我不知道如何获取路径/文件名。

我花了很多时间,想现在可能是问的好时机:

我该怎么做?

这是一个示例,仅用于演示输出。

#!/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

谢谢。

标签: bashshell

解决方案


要在终端上查看标准输出以及捕获/过滤器,一种没有 tmp 文件的方法是将任何 [实用程序或脚本]的输出tee /dev/tty通过管道传输到 ,同时将tee输出传输到过滤器,例如:

util | tee /dev/tty | grep '\.log$'

将上述内容捕获到 bash 变量中:

var=$(util | tee /dev/tty | grep '\.log$')

根据OP的描述,上面可以编写脚本,tee可以通过其他方法减少输出,复制日志文件,然后执行$EDITOR ./copy.log


推荐阅读