bash 在bash脚本中向日志文件添加时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19135124/
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
Adding time stamp to log file in bash script
提问by Joshua
My script is as follows
我的脚本如下
if ps ax | grep -v grep | grep ./program > /dev/null
then
exit
else
echo "---------------------------------------------------" >> Debug.log
echo "Starting program at: $(date)" >> Debug.log
./program >> Debug.log 2>&1
fi
exit
Via crontab, this script is run every minute. It checks to see if a certain program is running, if it is, great, if not, starts it up.
通过 crontab,这个脚本每分钟运行一次。它检查某个程序是否正在运行,如果是,很好,如果不是,则启动它。
Now I would like to append timestamps every time the script runs into Debug.log if it found ./program to be running. So under the then
line, I added:
现在我想在每次脚本运行到 Debug.log 时附加时间戳,如果它发现 ./program 正在运行。所以在这then
条线下,我补充说:
echo "Time: $(date)" >> Debug.log
This command does not output anything to Debug.log. It does work however directly from the command line. Why is that so, and can I remedy the problem?
此命令不会向 Debug.log 输出任何内容。但是它可以直接从命令行工作。为什么会这样,我可以解决这个问题吗?
回答by fedorqui 'SO stop harming'
Note you are outputting to Debug.log
, while you should indicate the full path of that file: echo "Time: $(date)" >> /path/to/Debug.log
.
请注意,您正在输出到Debug.log
,而您应该指出该文件的完整路径:echo "Time: $(date)" >> /path/to/Debug.log
。
In general, whenever you want to add timestamp to a log file, you can use:
通常,每当您想将时间戳添加到日志文件时,您可以使用:
echo "Time: $(date). Some error info." >> /path/to/your/file.log
date
will expand to something like Fri Sep 9 12:18:02 CEST 2016
. In that case, you may prefer to use some date
flags to have a more parseable date:
date
将扩展到类似Fri Sep 9 12:18:02 CEST 2016
. 在这种情况下,您可能更喜欢使用一些date
标志来获得更可解析的日期:
$ date "+%FT%T"
2016-09-09T12:18:23
Or, even better, using the ISO 8601format:
或者,更好的是,使用ISO 8601格式:
$ date -Iseconds
2016-09-09T12:18:23+0200
All together:
全部一起:
echo "Time: $(date -Iseconds). Some error info." >> /path/to/your/file.log
回答by Wintermute
Possible reason is different paths for date in terminal and sh: try using full path to the date which you use directly from command line, i.e. $(/bin/date)
可能的原因是终端和 sh 中的日期路径不同:尝试使用直接从命令行使用的日期的完整路径,即 $(/bin/date)