我正在尝试编写一个bash脚本,它将通过mac地址记录wifi连接的连接状态,但是我对代码的语法有些麻烦。
#!/bin/sh
client="E1:FA:41:23:00:AC"
logfile="/var/logs/wificonn.log"
timestamp=$(date +"%Y%d%m %T")
assoclist=$(wl assoclist | grep $client)
loglast=$(tail -n 1 $logfile | grep $client Not Connected)
notconnmsg="$timestamp $client Not Connected"
connmsg="$timestamp $client Connected"
if [ ! -f $logfile ]; then
touch $logfile
fi
if [ -z $assoclist ]; then # Client is not connected
if [ -n $loglast ]; then # Last log is connected show not connected message
echo $notconnmsg
echo $notconnmsg >> $logfile
fi
else # Client is connected
if [ -z $loglast ]; then # Last log is not connected show connected message
echo $connmsg
echo $connmsg >> $logfile
fi
fi
这将每隔60秒作为一个cron作业运行,并且只有在相反的情况下才显示/记录已连接或未连接的事件。我试图通过检查最后一个日志条目来实现这一点。例如,如果上次日志未连接且现已连接,请登录到文件。这就是问题所在。
感谢
答案 0 :(得分:1)
我改变了代码并获得了这个有效的解决方案以防任何人想要使用它
#!/bin/sh
client="XX:XX:XX:XX:XX:XX"
logfile="/var/log/wifilog-$(date +"%m%d")-$client.log"
assoclist=$(wl assoclist | grep $client)
notconnmsg="$(date +"%T") Disconnected"
connmsg="$(date +"%T") Connected"
if [ ! -f $logfile ]; then
echo $notconnmsg > $logfile
fi
if [ -z $assoclist ]; then # Client is not connected
echo $(tail -n 1 $logfile) - $notconnmsg
if [ -z $(tail -n 1 $logfile | grep "Disconnected") ]; then # Last log is connected show not connected message
echo $notconnmsg >> $logfile
fi
else # Client is connected
echo $(tail -n 1 $logfile) - $connmsg
if [ -z $(tail -n 1 $logfile | grep "Connected") ]; then # Last log is not connected show connected message
echo $connmsg >> $logfile
fi
fi
答案 1 :(得分:0)
if [ -n $loglast ]; then
尝试用双引号括起$loglast
:
if [ -n "$loglast" ]; then
当$loglast
为空时,bash会看到if [ -n ]
。你没有评估一个空参数,你什么也没有评估。您可以尝试以下方法来查看差异:
$ loglast=""
$ if [ -n "$loglast" ]; then echo 'yep'; fi
# <no output>
$ if [ -n $loglast ]; then echo 'yep'; fi
# yep