In many scenarios—like automation, cron jobs, or IoT devices—you need to verify internet connectivity before continuing a task. Using a Bash script is one of the fastest and most reliable ways to do this.
This post covers:
- How to write a Bash script to detect internet connection
- Different methods:
ping
,curl
,wget
- Real-world use cases and tips
✅ Method 1: Check Internet Using ping
This method is simple and works in most environments.
#!/bin/bash
ping -c 1 google.com > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Internet is available."
else
echo "Internet is NOT available."
fi
Explanation:
ping -c 1 google.com
sends one packet to Google> /dev/null 2>&1
hides the output$?
checks the exit status (0 = success)
✅ Method 2: Using curl
#!/bin/bash
curl -s --head http://www.google.com | grep "200 OK" > /dev/null
if [ $? -eq 0 ]; then
echo "Internet is available."
else
echo "Internet is NOT available."
fi
Note: This checks if HTTP headers respond with a success code.
✅ Method 3: Silent Check with wget
#!/bin/bash
wget -q --spider http://google.com
if [ $? -eq 0 ]; then
echo "Internet is available."
else
echo "Internet is NOT available."
fi
🔄 Use Cases
- 💻 Startup Scripts – Wait for internet before syncing backups
- 📦 IoT Devices – Check connectivity before sending data
- 🔄 Cron Jobs – Only run tasks if internet is available
- 🧪 System Monitoring – Detect connection loss with alerts
🧠 Bonus: Loop Until Internet Is Available
#!/bin/bash
until ping -c1 google.com &>/dev/null; do
echo "Waiting for internet..."
sleep 5
done
echo "Internet is available. Proceeding..."
⚠️ Tips and Best Practices
Tip | Benefit |
---|---|
Use -c 1 in ping to reduce delay | Faster response time |
Avoid hardcoding domains | Use DNS or IPs suited to your region |
Redirect output to /dev/null | Keeps your logs clean |
Use fallback domains | In case primary domain is unreachable |
Checking internet availability via a Bash script is a lightweight and efficient method suitable for servers, Linux-based devices, and automated tasks. You now know three ways to do it—use whichever best fits your environment!
Have a unique use case for checking internet with Bash?
Drop your example or enhancement in the comments below and share this post with your fellow Linux users! 📡🐧