【问题标题】:Shell script - Output to both the terminal and a log file in a sub-shellShell 脚本 - 输出到终端和子 shell 中的日志文件
【发布时间】:2020-12-15 22:32:27
【问题描述】:

我有一些旨在协同工作的 shell 脚本。第一个脚本 (script1.sh) 在子 shell 中调用下一个脚本。第二个脚本 (script2.sh) 需要“返回”一些内容以供第一个脚本使用。我需要在第二个脚本中回显的最后一行。但是,当我以这种方式使用它时,第二个脚本中通过 echo 的任何输出都不会输出到终端。我希望第一个和第二个(以及第三个和第四个...)的所有输出都输出到终端,但也写入日志文件。

script1.sh:

#!/bin/sh

func_one() {
   RESULT=$(./script2.sh | tail -1)
   echo "RESULT: $RESULT"
}

func_one | tee log_file.log

script2.sh:

#!/bin/sh

echo "Hello"
echo "World!"

尝试 1 输出:

$ ./script1.sh
RESULT: World!
$

log_file.log 内容:

RESULT: World!

如果我尝试在第二个脚本中重定向输出,那么它会输出到终端,但不会输出到日志文件:

script2.sh:

#!/bin/sh

echo "Hello" >&2
echo "World!" >&2

尝试 2 输出:

$ ./script1.sh
Hello
World!
RESULT:

log_file.log 内容:

RESULT:

我还尝试在脚本 1 的同一行输出到终端和 tee:

func_one >&2 | tee log_file.log

但这与第一次尝试的结果相同。

我想要的是将输出到终端并写入 .log 文件:(如果它工作正常)

$ ./script1.sh
Hello
World!
RESULT: World!
$

log_file.log 内容:

Hello
World!
RESULT: World!

我怎样才能得到这个结果?此外,最好不要使用 bash,因为我们将在其中运行它的一些机器没有 bash。

我看过这里: How do I get both STDOUT and STDERR to go to the terminal and a log file? 但这对我没有帮助。

【问题讨论】:

    标签: linux shell logging terminal subshell


    【解决方案1】:

    要让script2.sh的所有输出都发送到终端而不干扰script1.sh的工作,试试script1.sh的这个修改:

    $ cat script1.sh
    #!/bin/bash
    
    func_one() {
       RESULT=$(./script2.sh | tee >(cat >&2) | tail -1)
       echo "RESULT: $RESULT"
    }
    
    func_one | tee log_file.log
    

    在这里,第一个 tee 命令确保所有script2.sh 输出都通过 stderr 出现在终端上。为此,需要进程替换(而这又需要从sh 升级到bash)。

    输出是:

    $ ./script1.sh
    Hello
    World!
    RESULT: World!
    

    变化

    这与上面的相同,只是我们不涉及 stderr(您可能希望保留该错误)。在这里,我们创建了一个额外的文件描述符3,来复制标准输出:

    #!/bin/bash
    
    exec 3>&1
    func_one() {
       RESULT=$(./script2.sh | tee >(cat >&3) | tail -1)
       echo "RESULT: $RESULT"
    }
    
    func_one | tee log_file.log
    

    【讨论】:

      猜你喜欢
      • 2022-09-23
      • 1970-01-01
      • 2014-11-08
      • 1970-01-01
      • 2018-07-12
      • 2011-01-20
      • 2012-11-15
      • 2022-11-24
      • 1970-01-01
      相关资源
      最近更新 更多