When writing shell scripts, certain functionalities require ensuring that the server’s network can access the internet before proceeding. In such cases, you need a function to check the server’s network status. We can use curl to access www.google.com to determine if the server’s network is functioning properly.
How to Check If a Server’s Network Can Access the Internet Using a Linux Shell Script
You can run the following script to see if the server can access the internet.
<pre class="brush:bash;toolbar:false">#!/bin/bash #test network function network() { local timeout=1 #target website local target=www.google.com #get the response code local ret_code=`curl -I -s --connect-timeout ${timeout} ${target} -w %{http_code} | tail -n1` if [ "x$ret_code" = "x200" ]; then #The network is working fine return 1 else #The network is not working return 0 fi return 0 } network if [ $? -eq 0 ];then echo "The network is not working, please check your network settings!" exit -1 fi echo "The network is working fine, you can surf the internet!" exit 0</pre>
Script Execution Result When Network is Normal:
The network is working fine, you can surf the internet!
Script Execution Result When Network is Not Normal:
The network is not working, please check your network settings!