【问题标题】:Save terminal output coming from bash loop command保存来自 bash 循环命令的终端输出
【发布时间】:2018-02-08 23:56:59
【问题描述】:

我有一个这样的 bash 循环:

for f in *.fastq; do
echo $f
main command
done

我想将在我的终端中打印的任何内容(包括文件名和错误消息)打印到文本文件中。我怎样才能做到这一点?谢谢

【问题讨论】:

  • 如果您只是指 stdout 和 stderr,在 done 之后立即附加 > >(tee somefilename) 2>&1 就足够了。如果您真的指的是终端输出,例如包含直接写入/dev/tty 的内容(出于安全原因,通常明确地绕过日志记录或拦截),那么您需要使用scriptscreen(带有其日志记录选项)等工具。
  • 完美!谢谢!

标签: bash loops ubuntu unix


【解决方案1】:

如果您不想让stdoutstderr 一直显示在屏幕上,您可以在循环之后将stdoutstderr 重定向到覆盖 中的文件模式或追加模式分别使用:

for f in *.fastq; do
echo $f
main command
done > file.out 2>&1

for f in *.fastq; do
echo $f
main command
done >> file.out 2>&1

如果您想同时在屏幕上显示 stderr、stdout 并保存到文件中,请使用:

for f in *.fastq; do
echo $f
main command
done |& tee file.out

for f in *.fastq; do
echo $f
main command
done |& tee -a file.out

tee -a 在追加模式下运行 tee|&2>&1 | 的简写

阅读材料https://www.gnu.org/software/bash/manual/bash.html#Redirections https://unix.stackexchange.com/questions/24337/piping-stderr-vs-stdout

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2012-05-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    相关资源
    最近更新 更多