In my school, the internet is not available(every night after 23:0 the school will kill the internet, to put us in bed >..<), then the ping will never stop, though I have use
A variation on Majal's solution above is just to test the return code from ping, which returns 0 if the site responds, 1 if there is no reply and 2 if the network is unreachable.
ping -c 1 -t 5 8.8.8.8 2&>1
rc=$?
[[ $rc -eq 0 ]] && { echo "Connected to the Internet" ; exit 0 ; } \
|| [[ $rc -eq 1 ]] && { echo "No reply from Google DNS" ; exit 1 ; } \
|| [[ $rc -eq 2 ]] && { echo "Network unreachable" ; exit 2 ; }
Using ping has the advantage of not needing to download anything, improving the speed of the test.