【问题标题】:how to log several commands from a shell script to a log file如何将 shell 脚本中的多个命令记录到日志文件中
【发布时间】:2016-05-31 01:14:07
【问题描述】:

在 shell 文件中有几个命令,我想记录并在屏幕上显示。但有些命令结果我不想在屏幕上显示,有些我想显示 - 但它们都需要记录。

我可以使用 tee 或 > 或 >> 等。

script.sh | tee -a logfile

但这不允许我选择屏幕上显示的内容和日志中的内容。

示例脚本 - 我现在拥有的(每一行都不一样,看起来效率低下)

echo "setting date" | tee log.txt #show on screen and log
`date` | tee -a log.txt # screen and log
echo "setting name" | tee -a log.txt #show on screen  
`who am i` >> log.txt | only log

我有几个这样的命令 - 并且想知道是否有一种有效的方法可以在屏幕上显示时追加到日志和/或追加到日志。

或者我必须在每一行中修改并拨打电话吗?

用户将无法修改此脚本。

【问题讨论】:

  • ps:我理解使用 exec >> --> 但这不会显示任何内容。我想对显示的内容和不显示的内容有所选择。
  • 所以....在您不想记录的命令上,不要使用tee,而您想要记录的命令,请使用tee。你还在寻找什么?也许我不明白这个问题。
  • 我的问题是 - 我是否需要为 shell 脚本中的每个命令制作一个 tee 或 >> 参考?如果我有 20 个命令,那么每个命令都必须有一个 tee 或 >> ?
  • 您是否正在寻找类似stackoverflow.com/questions/20355264/… 的东西?
  • 是的...我的意思是,这很简单,对吧? command >> my.logcommand | tee -a my.logcommand 取决于您的需要。我想你可以写一个函数来接收标准输出和一个布尔值,不管你想不想记录它,但这似乎更麻烦。

标签: bash shell scripting ksh


【解决方案1】:

感谢您的回复。经过大量额外研究 - 我决定从How do I write stderr to a file while using "tee" with a pipe? 的答案中挑选部分内容 - 来自安东尼的帖子。

【讨论】:

    【解决方案2】:

    如果您不想用每个命令告诉您喜欢它记录的人,请决定您大部分时间要使用什么。是tee吗?试试这个:

    function doit {
       echo "Normal (both)"
       # Some more commands without explicit rediection for both strout and logfile
       echo "only stdout" >&3
       echo "Only logfile" >> $0.log
    }
    exec 3>&1
    echo " === Screen output"
    doit | tee -a $0.log
    echo " === Content file"
    cat $0.log
    

    输出

    === Screen output
    only stdout
    Normal (both)
     === Content file
    Only logfile
    Normal (both)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2015-09-09
      • 2017-06-16
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多