简体   繁体   English

Bash:循环直到命令退出状态等于 0

[英]Bash: Loop until command exit status equals 0

I have a netcat installed on my local machine and a service running on port 25565. Using the command:我在本地机器上安装了一个 netcat,并在端口 25565 上运行了一个服务。使用命令:

nc 127.0.0.1 25565 < /dev/null; echo $?

Netcat checks if the port is open and returns a 0 if it open, and a 1 if it closed. Netcat 检查端口是否打开,如果打开则返回 0,如果关闭则返回 1。

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).我正在尝试编写一个 bash 脚本来无限循环并每秒执行上述命令,直到命令的输出等于 0(端口打开)。

My current script just keeps endlessly looping "...", even after the port opens (the 1 becomes a 0).我当前的脚本只是不停地循环“...”,即使在端口打开之后(1 变为 0)。

until [ "nc 127.0.0.1 25565 < /dev/null; echo $?" = "0" ]; do
         echo "..."
         sleep 1
     done
echo "The command output changed!"

What am I doing wrong here?我在这里做错了什么?

Keep it Simple把事情简单化

until nc -z 127.0.0.1 25565
do
    echo ...
    sleep 1
done

Just let the shell deal with the exit status implicitly只是让 shell 隐式处理退出状态

The shell can deal with the exit status (recorded in $? ) in two ways, explicit, and implicit. shell 可以通过两种方式处理退出状态(记录在$? ),显式和隐式。

Explicit: status=$?显式: status=$? , which allows for further processing. ,这允许进一步处理。

Implicit:隐含:

For every statement, in your mind , add the word "succeeds" to the command, and then add if , until or while constructs around them, until the phrase makes sense.对于每个语句,在您的脑海中,在命令中添加单词“succeeds”,然后在它们周围添加ifuntilwhile构造,直到该短语有意义。

until nc succeeds ; do ...; done until nc成功; do ...; done ; do ...; done


The -z option will stop nc from reading stdin, so there's no need for the < /dev/null redirect. -z选项将阻止nc读取标准输入,因此不需要< /dev/null重定向。

You could try something like你可以尝试类似的东西

while true; do
    nc 127.0.0.1 25565 < /dev/null
    if [ $? -eq 0 ]; then
        break
    fi
    sleep 1
done
echo "The command output changed!"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM