While loop correction

I am checking if ssh is working fine on remote server proceed for next step until keep check ssh port, below is shell script.


#!/bin/bash

MON="SSH"

x=1
while [ "$MON" == "SSH" ]
do
  echo "SSH Checking Status"
  nc 192.168.1.20 -w 2
done

The while loop you have written is infinite loop, you need to add conditions to validate whether the ssh check was successful or not and if successful, break from the loop and proceed otherwise continue the loop.

i want to run this infinite. How?

while true
do
        # if exit code not 0 then next cmd also. break = end the while loop
        nc 192.168.1.20 -w 2 >/dev/null 2>&1  || break
        
done

Is same as

ok=1
while ((ok==1))
do
        # test cmd exist status
        if nc 192.168.1.20 -w 2 >/dev/null 2>&1 
        then 
             # still ok
             ok=1
        else
             ok=0
        fi
done

Is same as

ok=1
while ((ok==1))
do
        nc 192.168.1.20 -w 2 >/dev/null 2>&1 
        # save last cmd exit status
        stat=$?
        # and test it
        if ((stat==0))
        then 
             # still ok
             ok=1
        else
             ok=0
        fi
done

Or if you like to save cmd output and test it, then something

ok=1
while ((ok==1))
do
        output=$( nc 192.168.1.20 -w 2 2>/dev/null )  # err msg redirect to the /dev/null
        stat=$?
        # stat=0 =ok, other values not ok
        case "$output" in
              "") # empty
                  ok=1
                  ;;
              XXX*) ok=1 ;;
              *) ok=0 ;;
        fi
done