【问题标题】:Creating timestamps for "echo" outputs to file为“echo”输出创建时间戳到文件
【发布时间】:2019-07-30 14:41:23
【问题描述】:

我正在尝试为以下 .sh 文件在运行并执行“回声”时生成的信息创建时间戳。这样做的最佳方法是什么?

echo "Target File" >> /cygdrive/c/FilePath/Log.txt
if [ -f //TargetDirectory/TargetFile ]
then
    echo //TargetDirectory/TargetFile is present. >> /cygdrive/c/FilePath/Log.txt
else
    echo //TargetDirectory/TargetFile is missing. >> /cygdrive/c/FilePath/Log.txt
fi
echo -e "\n" >> /cygdrive/c/FilePath/Log.txt

【问题讨论】:

    标签: linux windows bash unix cygwin


    【解决方案1】:
    echo () {
        builtin echo "$(date +'[%m-%d %H:%M:%S]'):" "$@"
    }
    

    只需覆盖回声。

    【讨论】:

    • 这可能会更好builtin echo "$(date +'[%m-%d %H:%M:%S]'):" "$@"
    【解决方案2】:

    如果您想为脚本的所有输出(到STDOUT)加上时间戳,而不仅仅是echo产生的输出:

    #!/bin/bash
    
    timestamp () {
        while read -r line
        do
            echo "$(date --iso-8601=ns) $line"
        done
    }
    
    exec > >(timestamp)
    
    echo "Target File" >> /cygdrive/c/FilePath/Log.txt
    if [ -f //TargetDirectory/TargetFile ]
    then
        echo //TargetDirectory/TargetFile is present. >> /cygdrive/c/FilePath/Log.txt
    else
        echo //TargetDirectory/TargetFile is missing. >> /cygdrive/c/FilePath/Log.txt
    fi
    echo -e "\n" >> /cygdrive/c/FilePath/Log.txt
    printf '%s' "something"
    whoami
    

    如果您尝试分析脚本的执行,请参阅my answer here。

    【讨论】:

      【解决方案3】:

      我会写一个日志函数。

      function log()
      {
          echo "$(date +'[%m-%d %H:%M:%S]'):" $* >> /cygdrive/c/FilePath/Log.txt
      }
      
      log "Target File"
      if [ -f //TargetDirectory/TargetFile ]
      then
          log //TargetDirectory/TargetFile is present.
      else
          log //TargetDirectory/TargetFile is missing.
      fi
      log -e "\n"
      

      【讨论】:

      猜你喜欢
      • 2018-04-14
      • 2015-12-14
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多