如何创建每 5 分钟在日志文件中插入一条记录的 bash 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23982911/
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
How to create a bash script that every 5 minutes insert a record in a log file?
提问by AndreaNobili
I am very new into bash scripting and I need to create a simple script that every 5 minutes insert the date and time into a log file and save it.
我对 bash 脚本很陌生,我需要创建一个简单的脚本,每 5 分钟将日期和时间插入到日志文件中并保存。
What can I do to do it? From what can I start?
我该怎么做?我可以从什么开始?
回答by timgeb
The date
command will output the current date and time. You can append the output of a command to a file with >>
. Finally, sleep
will pause a script for a specified amount of seconds.
该date
命令将输出当前日期和时间。您可以将命令的输出附加到带有>>
. 最后,sleep
将暂停脚本指定的秒数。
#!/bin/bash
while true; do
date >> /path/to/the/logfile/dates.log
sleep 300
done
The date
command also provides options to modify the format of the output, if the optionless output does not suit your needs.
date
如果无选项输出不适合您的需要,该命令还提供修改输出格式的选项。
Alternatively, you could issue
或者,您可以发出
crontab -e
and add the line
并添加行
*/5 * * * * date >> /path/to/the/logfile/dates.log
Of course, you can use any name for your logfile, dates.log
is just the placeholder I used.
当然,您可以为日志文件使用任何名称,dates.log
这只是我使用的占位符。
回答by Kimmax
Write the bash script that does what you want and add the script to cron and set it to run every 5min.
编写执行所需操作的 bash 脚本,并将脚本添加到 cron 并将其设置为每 5 分钟运行一次。