Bash:将命令输出和时间戳附加到文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10838963/
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
Bash: Append command output and timestamp to file
提问by TCB13
Normally in my bash scripts I'm used to do some_command >> log.log. This works fine, however how can I append more data like time and command name?
通常在我的 bash 脚本中,我习惯于做some_command >> log.log. 这工作正常,但是如何附加更多数据,如时间和命令名称?
My goal is to have a log like this
我的目标是拥有这样的日志
2012-01-01 00:00:01 [some_command] => some command output...
2012-01-01 00:01:01 [other_command] => other command output...
The processes should running and writing to the file concurrently.
进程应该同时运行和写入文件。
The final solution, pointed by William Pursell in my case would be:
William Pursell 在我的案例中指出的最终解决方案是:
some_command 2>&1 | perl -ne '$|=1; print localtime . ": [somme_command] $_"' >> /log.log &
some_command 2>&1 | perl -ne '$|=1; print localtime . ": [somme_command] $_"' >> /log.log &
I also added 2>&1to redirect the STDOUTand STDERRto the file and an &on the end to keep the program on background.
我还添加2>&1了将STDOUT和重定向STDERR到文件并&在最后添加以将程序保持在后台。
Thank you!
谢谢!
采纳答案by William Pursell
Given your comments, it seems that you want multiple processes to be writing to the file concurrently, and have a timestamp on each individual line. Something like this might suffice:
鉴于您的评论,您似乎希望多个进程同时写入文件,并在每一行上都有一个时间戳。像这样的事情可能就足够了:
some_cmd | perl -ne '$|=1; print localtime . ": [some_cmd] $_"' >> logfile
If you want to massage the format of the date, use POSIX::strftime
如果要按摩日期的格式,请使用 POSIX::strftime
some_cmd | perl -MPOSIX -ne 'BEGIN{ $|=1 }
print strftime( "%Y-%m-%d %H:%M:%S", localtime ) . " [some_cmd] $_"' >> logfile
回答by estan
An alternative solution using sed would be:
使用 sed 的替代解决方案是:
some_command 2>&1 | sed "s/^/`date '+%Y-%m-%d %H:%M:%S'`: [some_command] /" >> log.log &
It works by replacing the beginning of line "character" (^). Might come in handy if you don't want to depend on Perl.
它的工作原理是替换行“字符”(^)的开头。如果您不想依赖 Perl,可能会派上用场。
回答by Cookie
On Ubuntu:
在 Ubuntu 上:
sudo apt-get install moreutils
echo "cat" | ts
Mar 26 09:43:00 cat
回答by johnshen64
something like this:
像这样:
(echo -n $(date); echo -n " ls => "; ls) >> /tmp/log
however, your command output is multiple lines and it will not have the format above you are showing. you may want to replace the newline in output with some other character with a command like tr or sed in that case.
但是,您的命令输出是多行,并且不会具有上面显示的格式。在这种情况下,您可能希望使用诸如 tr 或 sed 之类的命令将输出中的换行符替换为其他字符。
回答by DigitalRoss
One approach is to use logger(1).
一种方法是使用 logger(1)。
Another might be something like this:
另一个可能是这样的:
stamp () {
( echo -n "`date +%T` "
"$@" ) >> logfile
}
stamp echo how now brown cow

