如何让 for 循环输出一次而不是每次迭代?

How can I get a for loop to output once rather than every iteration?

我已经制作了这个简单的 bash 脚本来 运行 ping 扫描并获取网络上活动的 MAC 地址,输出到一个文件,然后将该文件与一个文件,其中包含我从路由器中的 ARP table 中获取的已知 MAC 地址列表。

我怎样才能让 for 循环吐出一个输出,如“所有设备在您的网络上都很熟悉”,而不是为它迭代的每一行回显结果?

当前代码:

sudo nmap -sn 192.168.0.0/24 | grep "MAC" | awk '{print }'| sort > $HOME/Desktop/arp.txt

readarray -t mac <$HOME/Desktop/arptable.txt

for address in "${mac[@]}"; do
    if grep -Fxq "$address" $HOME/Desktop/arptable.txt;
    then 
        echo "$address is a known network device"
    else
        echo "WARNING: $address is an unknown device on the network"
    fi
done 

我当前的输出如下:

XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device
XXXXXXXXXXXXXXXXX is a known network device

免责声明:这只是一个项目,并未用作严肃的安全工具。

假设您仍想打印出 WARNING 消息...跟踪成功次数,如果等于数组中的条目数 mac[] 则打印您想要的消息,例如:

found=0

for address in "${mac[@]}"; do
    if grep -Fxq "$address" $HOME/Desktop/arptable.txt;
    then 
        ((found++))
    else
        echo "WARNING: $address is an unknown device on the network"
    fi
done 

[[ "${found}" -eq "${#max[@]}" ]] && echo "All Devices are familiar on your network"

或者,如果您生成任何 WARNING 消息,请清除标志:

foundall=true

for address in "${mac[@]}"; do
    if ! grep -Fxq "$address" $HOME/Desktop/arptable.txt;
    then 
        echo "WARNING: $address is an unknown device on the network"
        foundall=false
    fi
done 

[[ "${foundall}" == 'true' ]] && echo "All Devices are familiar on your network"

伪代码(我不会bash,不懂语法):

sudo nmap -sn 192.168.0.0/24 | grep "MAC" | awk '{print }'| sort > $HOME/Desktop/arp.txt

readarray -t mac <$HOME/Desktop/arptable.txt

# everythingGood = true
for address in "${mac[@]}"; do
    if grep -Fxq "$address" $HOME/Desktop/arptable.txt;
    then 
    else
        # everythingGood = false
        # some code here maybe to store which ones failed
    fi
done 

# if everythingGood
    # echo "All Devices are familiar on your network"
# else
    # echo "WARNING: $address is an unknown device on the network"