为 "echo" 输出文件创建时间戳
Creating timestamps for "echo" outputs to file
我正在尝试为从下面的 .sh 文件生成的信息创建一个时间戳,当它是 运行 并且执行 "echo" 时。执行此操作的最佳方法是什么?
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
echo () {
builtin echo "$(date +'[%m-%d %H:%M:%S]'):" "$@"
}
只需覆盖 echo。
如果你想为你的脚本的 所有 输出(到 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。
我会写一个日志函数。
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"
我正在尝试为从下面的 .sh 文件生成的信息创建一个时间戳,当它是 运行 并且执行 "echo" 时。执行此操作的最佳方法是什么?
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
echo () {
builtin echo "$(date +'[%m-%d %H:%M:%S]'):" "$@"
}
只需覆盖 echo。
如果你想为你的脚本的 所有 输出(到 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。
我会写一个日志函数。
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"