有没有一种简单的方法来记录 shell 脚本所做的所有活动?

j0h*_*j0h 18 command-line bash scripts programming

是否有一种简单的方法可以将 shell 脚本中发生的所有活动记录到文件中?

我有一个脚本。它输出诸如 echo“指令”之类的内容,以及其他程序输出。我知道命令:

command | tee -a "$log_file"
Run Code Online (Sandbox Code Playgroud)

command >> logifle.log
Run Code Online (Sandbox Code Playgroud)

我要问的是是否有用于日志记录的 shell 参数,或者我可以使用的 set 命令或类似的东西。如果不需要,我不一定要向文件添加数十个重定向或 tee。我仍然想获得 std 输出 - 我也想记录它。:wq

A.B*_*.B. 20

有一个非常简单方便的方法:

使用script使终端会话的打字稿

  1. 启动命令 script

    如果file给出参数,例如script ~/tmp/outputscript将对话保存在此文件中。如果没有给出文件名,对话将保存在文件中typescript

  2. 启动您的脚本或您想启动的任何内容

  3. 如果您的脚本已完成,请script通过以下方式停止Ctrl-D

  4. 检查默认输出文件中的输出 typescript


script使用一步启动命令,请使用参数-c

-c COMMAND
    Run the COMMAND rather than an interactive 
    shell. This makes it easy for a script to capture
    the output of a program that behaves differently
    when its stdout is not a tty.
Run Code Online (Sandbox Code Playgroud)

的使用script内部脚本是没有意义的,因为script叉壳或启动一个新的外壳。

如果变量 SHELL 存在,则脚本派生的 shell 将是该 shell。如果未设置 SHELL,则假定为 Bourne shell。(大多数 shell 会自动设置此变量)。

  • @Fabby 我喜欢我的回答,但我没有看到灰色的小东西 ;) (4认同)

roa*_*dmr 18

如果您通常使用 运行脚本foo.sh,请尝试使用bash -x foo.sh. 如果您希望所有内容都重定向到文件,请尝试bash -x foo.sh > file.log 2>&1(注意我也在重定向 stderr,2>&1如果您不想要,请删除它)。如果你也想看看发生了什么,bash -x foo.sh 2>&1 | tee file.log.