我正在尝试编写一个记录连接状态的脚本,并作为cron作业运行。如果它获得了ip,它会将时间记录到文件中。
#!/bin/bash
ip=$(wget htt://checkip.dyndns.org/ -q -O - |
grep -Eo '\<[[:digit:]]{1,3}(\.[[:digit:]]{1,3}){3}\>')
echo $ip
if [ -n "$ip" ]
then
echo 'connected:'$(date +"%d-%m-%Y %I:%M") >> /home/saad/offline_check
else
echo 'disconnected:'$(date +"%d-%m-%Y %I:%M") >> /home/saad/offline_check
fi
此脚本将每隔5分钟将connected:XXXX
附加到文件中。我希望它写一次&amp;然后在发生断开连接之前不再进行日志记录。当连接恢复时,它应该将当前连接时间写在新行上。
这就是我想要的:
connected:08-02-2014 08:30 #start, all connected timestamps after initial one ignored
disconnected:09-02-2014 08:35 #disconnection logged
connected:09-02-2014 17:31 #when connection resumes, timestamp logged, all subsequent ignored until disconnect
disconnected:11-02-2014 08:31
我可以在python中执行此操作,但不能在bash中执行此操作。
答案 0 :(得分:1)
您可以在写入之前检查最后一行日志文件:
#!/bin/bash
ip=$(wget htt://checkip.dyndns.org/ -q -O - |
grep -Eo '\<[[:digit:]]{1,3}(\.[[:digit:]]{1,3}){3}\>')
# get the last line from log
line=$(tail -1 /home/saad/offline_check)
echo $ip
if [ -n "$ip" ]; then
# if last line starts with "disconnected" OR is empty then write "connected" log
[[ -z "$line" || "$line" == 'disconnected:'* ]] && \
echo 'connected:'$(date +"%d-%m-%Y %I:%M") >> /home/saad/offline_check
else
[[ "$line" == 'connected:'* ]] && echo 'disconnected:'$(date +"%d-%m-%Y %I:%M") >> /home/saad/offline_check
fi