Home > Software engineering >  Terminal Script not breaking after loop complete
Terminal Script not breaking after loop complete

Time:05-06

I am trying to write a terminal script; upon success I want to trigger a function and when it fails I want to send an alert. The script works except when it is successful it continues to run the commands after the 'done; line. Not sure of the proper syntax or correct way to write this.

I only want the commands after done to process upon failure, not success.

check_connection_wireguard(){
n=0
until [ "$n" -ge 1 ]
do
   ping -c 1 $remoteIdrac &> /dev/null && echo 'Success' && break
   n=$((n 1))
   echo "Connection Failed Attempt" $n
   sleep 15
done

   ssh $localIp wg-quick down $wireguardInterface
   ssh $localIp /usr/local/emhttp/webGui/scripts/notify -i alert -s \"Backup Remote Connection\" -d \"Backup Operation failed to connect\"
}

So I solved with below code, just added an if statement but wonder if there is a more elegant solution than below.

check_connection_wireguard(){
n=0
until [ "$n" -ge 1 ]
do
  ping -c 1 10.10.20.100 &> /dev/null && echo 'Success' && break
  n=$((n 1))
  echo "Connection Failed Attempt" $n
  sleep 15

    if [[ $n > 1 ]]; then
    ssh $localIp wg-quick down $wireguardInterface
    ssh $localIp /usr/local/emhttp/webGui/scripts/notify -i alert -s \"Backup Remote Connection\" -d \"Backup Operation failed to connect\"
    fi
done


}

CodePudding user response:

break only breaks out of the loop. You want return to break out of the function on success:

check_connection_wireguard(){
n=0
until [ "$n" -ge 1 ]
do
   ping -c 1 $remoteIdrac &> /dev/null && echo 'Success' && return
   n=$((n 1))
   echo "Connection Failed Attempt" $n
   sleep 15
done

   ssh $localIp wg-quick down $wireguardInterface
   ssh $localIp /usr/local/emhttp/webGui/scripts/notify -i alert -s \"Backup Remote Connection\" -d \"Backup Operation failed to connect\"
}
  • Related