Search code examples
linuxbashgrepconnectionping

Linux bash script to check internet connection not working


I want to use a bash script on my raspberry pi to check whether the internet connection is still present.

I found this script which I extended:

#!/bin/bash

# I do not work properly
if [[ "$(ping -c 1 8.8.8.8 | grep 'Network is unreachable' )" != "" ]]; then
    echo "Network isn't present"
    sudo shutdown -r 0
    exit 1
fi

# I work properly
if [[ "$(ping -c 1 8.8.8.8 | grep '100% packet loss' )" != "" ]]; then
    echo "Internet isn't present"
    sudo shutdown -r 0
    exit 1
else
    echo "Internet is present"
    exit 0
fi

The second part works nice, the first one, however, does not.

I unplugged my Ethernet cable and get an Error message like connect: Network is unreachable. So as expected. But I am not understanding why my script is not picking it up? I think it has something to do with it being an error message and not an output. But I do not know how I would have to adjust my script to grep from error messages as well, assuming this is correct.

I found a way how to get the output to be registered by grep by using this line ping -c 1 8.8.8.8 2> >(grep 'unreachable';). However, this still makes my script fail because it is no longer recognized by the rest of that line then. And I also do not entirely understand what 2> >() does.


Solution

  • You don't really need a string comparison here:

    ping command gives an appropriate return code after it completes execution.

    So, you could use something like:

     function check_connectivity() {
    
        local test_ip
        local test_count
    
        test_ip="8.8.8.8"
        test_count=1
    
        if ping -c ${test_count} ${test_ip} > /dev/null; then
           echo "Have internet connectivity"
        else
           echo "Do not have connectivity"
        fi
     }
    
     check_connectivity