What does the "!" in `while ! nc ...; do...; done` mean
Asked Answered
C

1

5

I am pretty new to bash, and I come across this code.

j=0
while ! nc -z "$host" "$port"; do
  j=$((j+1))
  if [ $j -ge 10 ]; then
    echo >&2 "$host:$port not reachable, giving up"
    exit 1
  fi
done

I cannot understand how the ! before the nc work here. Can anyone help explain that?

Thanks

Cantoris answered 9/11, 2018 at 0:54 Comment(0)
P
10

Here, ! is a keyword (thanks to user1934428 for the correction) which performs a NOT operation.

If the command nc -z "$host" "$port" didn't performed successfully, it would return "false" (i.e. a non-zero value). Hence, the ! [nc command] would return "true" (i.e. zero).

So it's like "while this nc command fails, do the loop. After ten tries ($j is greater than or equal to 10), give up".

You might want to have a peek on this interactive tutorial and this Wikibook.

Peptone answered 9/11, 2018 at 1:3 Comment(4)
Thank you! It is really clear. Also, these two resources are awesome!Cantoris
@Peptone : Minor correction - the ! is not an operator, but is considered (by bash and zsh as well) as a shell keyword (similar to time). You can see it when doing a type '!'.Jerome
@Xinbin, I figured out I wrote a huge typo. Of course if the nc command performed succesfully, ! nc would return false. I've edited my answer.Peptone
@Amessihel, thanks for the update! Though it doesn't affect my understanding of the logic, I should for sure learning the true concept... especially for such a newbie like meCantoris

© 2022 - 2024 — McMap. All rights reserved.