1

我正在尝试编写一个 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

这将作为 cron 作业每 60 秒运行一次,并且仅在相反的情况下才希望它显示/记录已连接或未连接的事件。我试图通过检查最后一个日志条目来实现这一点。例如,如果最后一个日志未连接而现在已连接,则记录到文件。这就是问题所在。

谢谢

4

2 回答 2

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
于 2012-09-19T22:13:08.490 回答
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
于 2012-09-19T04:13:20.650 回答