How to check internet access using bash script in linux?

前端 未结 10 1397
孤街浪徒
孤街浪徒 2021-02-01 06:43

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

10条回答
  •  感动是毒
    2021-02-01 07:03

    Reliable old ping in a separate bash script:

    #!/bin/bash
    ipaddr='8.8.8.8' # Google's public DNS server
    [[ -z `ping -c1 $ipaddr |& grep -o 'Network is unreachable'` ]] || exit 1
    [[ -z `ping -c3 $ipaddr |& grep -o '100% packet loss'` ]] && exit 0 || exit 1
    

    Put this on a separate script. It will handle different network situations as (1) not being connected to a network, (2) connected to the network but cannot access the internet (or at least Google), and (3) connected to the internet.


    You may later use the exit code of the script to check connectivity, e.g.

    ~$ script-name && echo online || echo offline
    

提交回复
热议问题