在Bash脚本条件下组合Grep检查



我确实有egrep(即grep -E)可用,我确信这是可能的,但我花了太多时间试图弄清楚如何一行。Awk也是grep的一个可接受的替代方案。

有人想把它变成一个"until"声明吗?两个grep查询都需要存在于xrandr输出中,而不是只有一个或另一个。

while true ; do
if xrandr | grep -q "primary 720x720+0+0" ; then
if xrandr | grep -q "connected 512x512+720+0" ; then
return
fi
fi
...
done

grep不适合这个任务。你可以使用awk:

if xrandr | awk '
/primary 720x720[+]0[+]0/ { found_a=1 }
/connected 512x512[+]720[+]0/ { found_b=1 }
END { if (found_a && found_b) { exit(0) } else { exit(1) } }
'; then
echo "Yes, found both strings"
else
echo "No, did not find both strings"
fi

…或者你可以直接在shell中执行你的逻辑:

xrandr_out=$(xrandr)
if [[ $xrandr_out = *"primary 720x720+0+0"* ]] 
&& [[ $xrandr_out = *"connected 512x512+720+0"* ]]; then
echo "Yes, found both strings"
else
echo "No, did not find both strings"
fi

无论哪种方法,最简单的方法就是将逻辑嵌入到函数中:

xrandr_all_good() {
xrandr | awk '
/primary 720x720[+]0[+]0/ { found_a=1 }
/connected 512x512[+]720[+]0/ { found_b=1 }
END { if (found_a && found_b) { exit(0) } else { exit(1) } }
'
}
until xrandr_all_good; do
: "...stuff here..."
done

最新更新