The Linux shell script checks that the network is normal

introduce

When writing shell scripts, some functions need to ensure that the server network is accessible to the Internet before they can be executed. In this case, a function is needed to determine the server network status

Using curl, you can visit www.baidu.com to check whether the network status of the server can be unblocked

Network state judgment

#! /bin/bash

#Check the network connectionFunction network() {# localtimeout =1 # localtarget =www.baidu.com # localret_code = 'curl i-s' --connect-timeout ${timeout} ${target} -w %{http_code} | tail -n1` if [ "x$ret_code" = "x200" ]; Network if [$? -eq 0]; network if [$? -eq 0]; Then echo "Check the network Settings!" Exit-1 Fi Echo "Internet connectivity, you can surf the Internet!" exit 0Copy the code

Network status normal script execution result: network smooth, you can surf the Internet!

Abnormal network status Script execution result: The network is abnormal. Check the network Settings.