问题描述
我在本地计算机上安装了netcat,并在端口25565上运行了服务.使用命令:
I have a netcat installed on my local machine and a service running on port 25565. Using the command:
nc 127.0.0.1 25565 < /dev/null; echo $?
Netcat检查端口是否打开,如果打开则返回0,如果关闭则返回1.
Netcat checks if the port is open and returns a 0 if it open, and a 1 if it closed.
我正在尝试编写一个bash脚本以进行无限循环,并每秒执行一次以上命令,直到命令的输出等于0(端口打开)为止.
I am trying to write a bash script to loop endlessly and execute the above command every second until the output from the command equals 0 (the port opens).
即使端口打开(1变为0),我当前的脚本也一直不断循环"...".
My current script just keeps endlessly looping "...", even after the port opens (the 1 becomes a 0).
until [ "nc 127.0.0.1 25565 < /dev/null; echo $?" = "0" ]; do
echo "..."
sleep 1
done
echo "The command output changed!"
我在做什么错了?
推荐答案
保持简单
until nc -z 127.0.0.1 25565
do
echo ...
sleep 1
done
只需让shell隐式处理退出状态
shell可以通过显式和隐式两种方式处理退出状态(记录在 $?
中).
The shell can deal with the exit status (recorded in $?
) in two ways, explicit, and implicit.
显式: status = $?
,可以进行进一步处理.
Explicit: status=$?
, which allows for further processing.
隐含:
对于每个陈述,在您的脑海中,在单词成功"之后添加到命令,然后添加 if
,直到
或 while
在它们周围构造,直到该短语有意义为止.
For every statement, in your mind, add the word "succeeds" to the command, and then addif
, until
or while
constructs around them, until the phrase makes sense.
直到nc
成功 ;做 ...;完成
-z
选项将阻止 nc
读取stdin,因此不需要</dev/null
重定向.
The -z
option will stop nc
from reading stdin, so there's no need for the < /dev/null
redirect.
这篇关于重击:循环直到命令退出状态等于0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!