Bash
日期字元串未在 while true 內更新;做循環
我有一個簡單的 bash 腳本:
#!/bin/bash enp="$(ip route | grep "192.168.1.1" | cut -d' ' -f 3)" while true; do vnstat -l -i "$enp" --style 4 --json | awk '{ print strftime("[%d/%b/%Y:%H:%M:%S]"), $0 }' >> raw/caching_server_network.json printf -- '-%.0s' {1..100}; echo "" >> raw/caching_server_network.json sleep 10 done
目前,此腳本會在每個 vnstat 輸出的開頭附加一個 strftime,並且每次呼叫都會更新 strftime。輸出:
[04/Jan/2022:13:31:17] {"index":1012,"seconds":2024,"rx":{"ratestring":"13.59 Mbit/s","bytespersecond":1698943,"packetspersecond":15220,"bytes":3397887,"packets":30441,"totalbytes":29895276777,"totalpackets":43496469},"tx":{"ratestring":"2.81 Gbit/s","bytespersecond":350918926,"packetspersecond":233842,"bytes":701837853,"packets":467685,"totalbytes":518923724379,"totalpackets":354639132}} [04/Jan/2022:13:31:41] {"index":1013,"seconds":2026,"rx":{"ratestring":"206.68 Mbit/s","bytespersecond":25834765,"packetspersecond":31840,"bytes":51669531,"packets":63681,"totalbytes":29946946308,"totalpackets":43560150},"tx":{"ratestring":"3.15 Gbit/s","bytespersecond":394123782,"packetspersecond":269030,"bytes":788247565,"packets":538060,"totalbytes":519711971944,"totalpackets":355177192}}
我想做的是讓 datetime 字元串包含毫秒。但我面臨的問題是日期輸出不再更新。每次呼叫只是將相同的時間添加到字元串中。
我嘗試了以下方法:
#!/bin/bash enp="$(ip route | grep "192.168.1.1" | cut -d' ' -f 3)" while true; do vnstat -l -i "$enp" --style 4 --json | awk '{ print "'"$(date +%F:%T.%3N)"'", $0 }' >> raw/caching_server_network.json printf -- '-%.0s' {1..100}; echo "" >> raw/caching_server_network.json sleep 10 done
輸出:
04/Jan/2022:13:30:11.743 {"index":975,"seconds":1950,"rx":{"ratestring":"73.04 Mbit/s","bytespersecond":9130121,"packetspersecond":25590,"bytes":18260242,"packets":51181,"totalbytes":29368713172,"totalpackets":42315654},"tx":{"ratestring":"3.90 Gbit/s","bytespersecond":486961964,"packetspersecond":326200,"bytes":973923928,"packets":652400,"totalbytes":498158299423,"totalpackets":340676257}} 04/Jan/2022:13:30:11.743 {"index":976,"seconds":1952,"rx":{"ratestring":"12.23 Mbit/s","bytespersecond":1529119,"packetspersecond":17962,"bytes":3058239,"packets":35924,"totalbytes":29371771411,"totalpackets":42351578},"tx":{"ratestring":"4.18 Gbit/s","bytespersecond":522336815,"packetspersecond":346742,"bytes":1044673631,"packets":693484,"totalbytes":499202973054,"totalpackets":341369741}}
請注意,上述輸出中的日期時間對於兩行來說是相同的。在使用日期呼叫時,如何獲取每個 vnstat 呼叫更新的日期?
每次呼叫的時間都會改變
vnstat
,但如果vnstat
輸出多行,它們都會收到相同的時間。這是因為 shell 執行date
並將其輸出插入到 的參數中awk
。要為每一行獲取新的時間戳,您需要呼叫
date
from withinawk
。由於我vnstat
的機器上沒有,我創建了一個更簡單的範例:#! /bin/bash while true; do for i in {1..3} ; do echo $i sleep .1 done | awk '{ system("date +%F:%T.%3N\\ | tr -d \\\\n"); print $0 }' printf -- '-%.0s' {1..80}; echo "" sleep 1 done
刪除時間戳後的
tr
換行符。