[英]how to add timestamp to the result of bash command for logging that can to file and screen
此链接无法完美解决我的问题如何为STDERR重定向添加时间戳
第一个问题:我不想要命令的输出,该命令在每行中添加时间戳,我只想在第一行中添加时间戳,如图所示
第二个问题:我执行脚本后,必须按Enter键才能结束该过程,如何解决此处输入图像的描述
#!/bin/bash exec > >(xargs -L1 -I{} bash -c "echo \\$(date +'%x %T') '{}'" | tee error.log) 2>&1 errorcommand pwd ifconfig ls
output:
root@xintian-desktop:~# bash exec.sh
2017年03月19日 10:31:51 exec.sh: line 3: asdsad: command not found
root@xintian-desktop:~# 2017年03月19日 10:31:51 /root
2017年03月19日 10:31:51 enxb827eb65188e Link encap:Ethernet HWaddr b8:27:eb:65:18:8e
2017年03月19日 10:31:51 UP BROADCAST MULTICAST MTU:1500 Metric:1
2017年03月19日 10:31:51 RX packets:0 errors:0 dropped:0 overruns:0 frame:0
2017年03月19日 10:31:51 TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
2017年03月19日 10:31:51 collisions:0 txqueuelen:1000
2017年03月19日 10:31:51 RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
2017年03月19日 10:31:51 lo Link encap:Local Loopback
2017年03月19日 10:31:51 inet addr:127.0.0.1 Mask:255.0.0.0
2017年03月19日 10:31:51 inet6 addr: ::1/128 Scope:Host
2017年03月19日 10:31:51 UP LOOPBACK RUNNING MTU:65536 Metric:1
2017年03月19日 10:31:51 RX packets:425 errors:0 dropped:0 overruns:0 frame:0
2017年03月19日 10:31:51 TX packets:425 errors:0 dropped:0 overruns:0 carrier:0
2017年03月19日 10:31:51 collisions:0 txqueuelen:0
2017年03月19日 10:31:51 RX bytes:34225 (34.2 KB) TX bytes:34225 (34.2 KB)
2017年03月19日 10:31:51 wlan0 Link encap:Ethernet HWaddr b8:27:eb:30:4d:db
2017年03月19日 10:31:51 inet addr:192.168.88.26 Bcast:192.168.88.255 Mask:255.255.255.0
2017年03月19日 10:31:51 inet6 addr: fe80::11f7:7058:ec37:3064/64 Scope:Link
2017年03月19日 10:31:51 UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
2017年03月19日 10:31:51 RX packets:342872 errors:0 dropped:203 overruns:0 frame:0
2017年03月19日 10:31:51 TX packets:17631 errors:0 dropped:0 overruns:0 carrier:0
2017年03月19日 10:31:51 collisions:0 txqueuelen:1000
2017年03月19日 10:31:51 RX bytes:69917459 (69.9 MB) TX bytes:2141207 (2.1 MB)
2017年03月19日 10:31:51 20150305
2017年03月19日 10:31:51 20150405
2017年03月19日 10:31:51 20150505
2017年03月19日 10:31:51 aaa
2017年03月19日 10:31:51 aaa.bak
2017年03月19日 10:31:51 asd
2017年03月19日 10:31:51 error.log
2017年03月19日 10:31:51 exec.sh
2017年03月19日 10:31:51 nohup.out
2017年03月19日 10:31:51 python_act
2017年03月19日 10:31:51 sec
2017年03月19日 10:31:51 stderr.log
2017年03月19日 10:31:51 trap.sh
为了回答您的第一个问题,我通常在脚本的输出中添加一条时间戳记行,尤其是那些定期运行的脚本。 有很多方法可以做到这一点。 这是我通常做的事情:
DATE=`date`
echo "------------------- $DATE -------------------"
关键是执行date
命令并以所需的任何格式打印输出。
最简单的方法是简单地自己执行date
,而不将输出存储在变量中,然后添加额外的字符(在上面的代码片段中,我添加了额外的“-”字符以使时间戳记行在日志中突出显示)。 例如,
date
您还可以使用更现代的形式将输出存储在变量中:
DATE=$(date)
当然,您可以根据需要设置时间戳记行的格式,例如,
echo "== $0 running $DATE =="
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.