我在bash中有以下循环:
sudo iwlist wlan0 scan | grep somewifi | while read -r line; do
检查所有带有“somewifi”的wifi并做一些事情。如果grep somewifi出现空,即未找到,如何退出程序
#!/usr/bin/env bash
# ^^^^- NOT /bin/sh
target=somewifi
found=0
while read -r line; do
if [[ $line = *"$target"* ]]; then
echo "Doing something with $line"
found=1
fi
done < <(sudo iwlist wlan0 scan)
if (( found == 0 )); then
echo "$target not found" >&2
exit 1
fi
我们在这里做的是通过在主shell中执行BashFAQ #24循环而不是子shell(通过管道进入while
循环创建)来避免while read
。这让我们可以在循环中设置变量,这些变量在退出后仍然存在。