Sometimes, you need to run a scheduled task only when your Linux machine is connected to the internet — like syncing files, backing up to cloud storage, or fetching API data. Cron alone doesn't have built-in network awareness, but you can achieve this using a simple shell script wrapper.
1. Check for Internet Connection
We'll write a shell script that checks for connectivity before running your main command. Here’s an example:
#!/bin/bash
# Test network availability by pinging a reliable server
if ping -q -c 1 -W 1 8.8.8.8 > /dev/null; then
echo "Internet available. Running job..."
/path/to/your/main/task.sh
else
echo "No internet. Skipping job."
fi
Make the script executable:
chmod +x /usr/local/bin/net-aware-job.sh
2. Set Up the Cron Job
Now schedule your cron job to run the above script regularly. Edit your crontab with:
crontab -e
Then add a line like this:
*/15 * * * * /usr/local/bin/net-aware-job.sh >> /var/log/net-job.log 2>&1
This will attempt to run your job every 15 minutes — but only if the internet is up.
3. Optional: Use a DNS Check Instead
If you prefer not to ping an IP, you can test DNS resolution instead:
if host google.com > /dev/null; then
# Run your job
fi
4. Use Cases
- Cloud backups with
rclone
- Database syncs to remote hosts
- Fetching web data
- Triggering webhook-based processes
Conclusion
This is a simple way to give your cron jobs network awareness without using heavy tooling or monitoring services. With just a few lines of shell script, your jobs can be smarter and more reliable in variable environments.
If you found this helpful, consider supporting me: buymeacoffee.com/hexshift