BASH

Check Internet Connectivity and Implement Retry Logic

Develop robust Bash scripts that can reliably check for internet access and incorporate retry mechanisms for operations dependent on network availability.

#!/bin/bash

TARGET_HOST="8.8.8.8" # Google's DNS server
MAX_RETRIES=10
RETRY_INTERVAL=5 # seconds

check_internet() {
  ping -c 1 "$TARGET_HOST" > /dev/null 2>&1
  return $?
}

echo "Checking internet connectivity..."

for i in $(seq 1 $MAX_RETRIES);
do
  if check_internet;
  then
    echo "Internet is up!"
    break
  else
    echo "Attempt $i/$MAX_RETRIES: Internet is down. Retrying in $RETRY_INTERVAL seconds..."
    sleep $RETRY_INTERVAL
  fi

  if [ $i -eq $MAX_RETRIES ]; then
    echo "Failed to connect to the internet after $MAX_RETRIES attempts. Exiting."
    exit 1
  fi
done

echo "
--- Internet connectivity established. Proceeding with script logic ---"
# Add your network-dependent commands here
# For example, a curl command to fetch data
# curl -s 'https://example.com/api/data'
How it works: This script defines a `check_internet` function that attempts to `ping` a reliable host (like Google's DNS) and checks its exit status. A `for` loop then retries this check up to a `MAX_RETRIES` limit, pausing for `RETRY_INTERVAL` seconds between attempts. This pattern is crucial for scripts that need to perform network operations, ensuring they wait for connectivity to be established before proceeding, preventing failures due to temporary network outages. If connectivity isn't achieved after all retries, the script exits with an error.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs