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
Similarly to @Jesse's answer, this option might be much faster than any solution using ping
and perhaps slightly more efficient than @Jesse's answer.
find /sys/class/net/ -maxdepth 1 -mindepth 1 ! -name "*lo*" -exec sh -c 'cat "$0"/carrier 2>&1' {} \; | grep -q '1'
This command uses find
with -exec
to run command on all files not named *lo*
in /sys/class/net/
. These should be links to directories containing information about the available network interfaces on your machine.
The command being ran is an sh
command that checks the contents of the file carrier
in those directories. The value of $interface/carrier
has 3 meanings - Quoting:
It seems there are three states:
- ./carrier not readable (for instance when the interface is disabled in Network Manager).
- ./carrier contain "1" (when the interface is activated and it is connected to a WiFi network)
- ./carrier contain "0" (when the interface is activated and it is not connected to a WiFi network)
The first option is not taken care of in @Jesse's answer. The sh
command striped out is:
# Note: $0 == $interface
cat "$0"/carrier 2>&1
cat
is being used to check the contents of carrier
and redirect all output to standard output even when it fails because the file is not readable.
If grep -q
finds "1"
among those files it means there is at least 1 interface connected. The exit code of grep -q
will be the final exit code.
For example, using this command's exit status, you can use it start a gnubiff in your ~/.xprofile
only if you have an internet connection.
online() {
find /sys/class/net/ -maxdepth 1 -mindepth 1 ! -name "*lo*" -exec sh -c 'cat "$0"/carrier 2>&1 > /dev/null | grep -q "1" && exit 0' {} \;
}
online && gnubiff --systemtray --noconfigure &