Bash: Loop until command exit status equals 0

后端 未结 2 901
名媛妹妹
名媛妹妹 2021-02-07 04:53

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 $?
<
相关标签:
2条回答
  • 2021-02-07 05:11

    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

    The shell can deal with the exit status (recorded in $?) in two ways, explicit, and implicit.

    Explicit: 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.

    until nc succeeds; do ...; done


    The -z option will stop nc from reading stdin, so there's no need for the < /dev/null redirect.

    0 讨论(0)
  • 2021-02-07 05:11

    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!"
    
    0 讨论(0)
提交回复
热议问题