How to test an Internet connection with bash?

后端 未结 19 1490
青春惊慌失措
青春惊慌失措 2020-11-27 09:26

How can an internet connection be tested without pinging some website? I mean, what if there is a connection but the site is down? Is there a check for a connection with the

19条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 10:17

    Without ping

    #!/bin/bash
    
    wget -q --spider http://google.com
    
    if [ $? -eq 0 ]; then
        echo "Online"
    else
        echo "Offline"
    fi
    

    -q : Silence mode

    --spider : don't get, just check page availability

    $? : shell return code

    0 : shell "All OK" code

    Without wget

    #!/bin/bash
    
    echo -e "GET http://google.com HTTP/1.0\n\n" | nc google.com 80 > /dev/null 2>&1
    
    if [ $? -eq 0 ]; then
        echo "Online"
    else
        echo "Offline"
    fi
    

提交回复
热议问题