Bash: Loop until command exit status equals 0

后端 未结 2 895
名媛妹妹
名媛妹妹 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.

提交回复
热议问题