Martynas回答的进一步简化:
until ping -c1 www.google.com &>/dev/null; do :; done
请注意,ping本身用作循环测试;一旦成功,循环结束.循环体是空的,使用null命令“:”来防止语法错误.
更新:我想到了一种让Control-C干净地退出ping循环的方法.这将在后台运行循环,捕获中断(Control-C)信号,并在发生时终止后台循环:
ping_cancelled=false # Keep track of whether the loop was cancelled,or succeeded
until ping -c1 "$1" &>/dev/null; do :; done & # The "&" backgrounds it
trap "kill $!; ping_cancelled=true" SIGINT
wait $! # Wait for the loop to exit,one way or another
trap - SIGINT # Remove the trap,now we're done with it
echo "Done pinging,cancelled=$ping_cancelled"
它有点迂回,但是如果你想让循环可以取消它应该可以解决问题.