将 bash 脚本的每个命令的 stdout 和 stderr 的输出附加到文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40848238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:28:17  来源:igfitidea点击:

Append output from both stdout and stderr of every command of a bash script to file

bashmacosredirectstdoutstderr

提问by Paolo

Here

这里

https://stackoverflow.com/a/876267/1579327

https://stackoverflow.com/a/876267/1579327

I learned how to do that for a single command cmdappending output to file.txt

我学会了如何为单个命令cmd将输出附加到file.txt

cmd >>file.txt 2>&1

But my script contains many statements and commands.

但是我的脚本包含许多语句和命令。

And I would like to avoid appending >>file.txt 2>&1to every line.

我想避免附加>>file.txt 2>&1到每一行。

Is there a directive to let me to do that by default for every subsequent command?

是否有指令让我默认为每个后续命令执行此操作?



Side note: I'm looking for a solution suitable also for MacOs X's bash

旁注:我正在寻找一种也适用于 MacOs X 的 bash 的解决方案

回答by anubhava

On top of your script you can use execlike this:

在您的脚本之上,您可以exec像这样使用:

#!/bin/bash

# append stdout/stderr to a file
exec >> file.log 2>&1

# script starts here