基于条件的bash脚本行替换

基于条件的bash脚本行替换,bash,Bash,我正在尝试编写一个脚本,记录连接状态并作为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")

我正在尝试编写一个脚本,记录连接状态并作为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

我可以在python中这样做,但不能在bash中这样做。

您可以在写入日志文件之前检查日志文件的最后一行:

#!/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
#/bin/bash
ip=$(wget)htt://checkip.dyndns.org/ -q-O-|
grep-Eo'\')
#从日志中获取最后一行
行=$(尾部-1/主/saad/脱机检查)
echo$ip
如果[-n“$ip”];然后
#如果最后一行以“disconnected”开头或为空,则写入“connected”日志
[[-z“$line”| |“$line”=='断开:'*]&&\
echo“已连接:”$(日期+%d-%m-%Y%I:%m”)>>/home/saad/offline\u检查
其他的
[[“$line”=='已连接:'*]&&echo'已断开:'$(日期+%d-%m-%Y%I:%m”)>/home/saad/offline\u检查
fi

如果您在
bash
中做了这么多,并且可以在
python
中完成,那么我看不出您有什么理由不能完成它。不?我根本不在bash工作。这个脚本是别人的。我必须学习整个结构。对于后代,还要将else语句编辑为
[[“$line”='connected:'*]]和&echo'disconnected:'$(date+%d-%m-%Y%I:%m”)>/home/saad/offline\u check
,以避免日志中出现大量
已断开连接的消息。
#!/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