将脚本的所有输出捕获到文件中(从脚本本身)

Dr.*_*ini 11 bash string files output

我有一个 bash 脚本,它调用各种命令并打印一些输出(来自被调用的命令本身,例如git pull,以及脚本本身生成的信息性消息,例如Operation took XX minutes.

我想整个输出捕获到文件,从脚本本身:基本上我试图避免需要调用./myscript.sh | tee file.txt非相关,在这里的原因。

基本上我想做这样的事情:

startCapture

git pull

echo "Text"

other-command

endCapture
Run Code Online (Sandbox Code Playgroud)

我还要求在脚本运行时将输出打印在我的 shell 上。

最终目标是:

  1. ./myscript.sh无需额外的 shell 结构即可运行
  2. 像我现在一样查看终端上的输出
  3. 在磁盘上获取包含整个输出的文件

这甚至可能吗?

Rui*_*iro 8

您始终可以script在脚本内部调用来记录所有内容。

至于在 bash 脚本中同时打印和记录所有内容log.txt

#!/bin/bash

if [ -z "$SCRIPT" ]
then 
    /usr/bin/script log.txt /bin/bash -c "$0 $*"
    exit 0
fi

echo teste
Run Code Online (Sandbox Code Playgroud)

查看日志log.txt

$ ./a.sh
Script started, output file is log.txt
teste

Script done, output file is log.txt
$ cat log.txt
Script started on Fri Feb 16 17:57:26 2018
command: /bin/bash -c ./a.sh 
teste

Script done on Fri Feb 16 17:57:26 2018
Run Code Online (Sandbox Code Playgroud)

  • 如果我理解正确(一些解释会有所帮助:),脚本会尝试检测它是否在“script”下运行,而不是重新执行自身。从 Ubuntu 20 开始,似乎未设置“$SCRIPT”,因此脚本进入无限循环。 (8认同)
  • 不过,使用“脚本”是个好主意,因为它允许交互式终端输出(例如回车符)工作。实际上,显示单行进度输出的命令(例如归档器)[表现正常](https://unix.stackexchange.com/questions/67652/copy-stdout-and-stderr-to-a-log-文件并将其保留在 sc/164017#comment1100241_164017 内的控制台上)。至于解决无限循环问题,我们可以【测试shell级别】(https://unix.stackexchange.com/questions/162839/how-can-a-bash-script-tell-how-it-was-run /474293#474293): `if (( $SLVL < 3 )); 然后编写脚本...;fi`。 (4认同)

the*_*btm 2

我发现捕获任何会话的所有输出的方法是启动一个新的 bash 会话并发送到日志文件。它对于跟踪不仅仅是一个脚本确实很有用。

bash | tee ~/bash.log #这将保存标准输出,直到 bash 会话结束
bash 2>&1 | bash 2>&1 | tee ~/bash.log #这将保存所有输出,包括错误,直到 bash 会话结束

或者你可以直接编写脚本

./myscript.sh | tee ./myscript.log #this will log only the output of the script.