Search code examples
bashnetcat

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


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


Solution

  • 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.