]> git.sthu.org Git - shutils.git/commitdiff
ifonline: Check for default route
authorStefan Huber <shuber@sthu.org>
Sun, 14 Jul 2019 10:20:15 +0000 (12:20 +0200)
committerStefan Huber <shuber@sthu.org>
Sun, 14 Jul 2019 10:24:10 +0000 (12:24 +0200)
ifonline

index 5a262159bf653e490991fc4744196bcabf528ef5..8bb8ae74c519416a99a83fc11a8220f46beed07e 100755 (executable)
--- a/ifonline
+++ b/ifonline
@@ -1,7 +1,13 @@
 #!/bin/sh
 
+set -e
+
 usage() {
-       cat << EOF
+  cat << EOF
+Executes a given command if there is an internet connection. Availability of an
+connection is tested by (i) the availability of a default route and (ii) the
+pingability of a test host.
+
 Usage:
  $0 [OPTIONS]
  $0 -h
@@ -9,31 +15,54 @@ Usage:
 
 OPTIONS:
   -h            Show this text
+  -v            Verbose output
+  -p HOST       Host for ping test. Default: 8.8.8.8
   -c CMD        Command to execute if online
 EOF
 }
 
 CMD=""
+VERBOSE=0
+PINGHOST="8.8.8.8"
 
-while getopts "hc:" OPTION; do
+while getopts "hvc:p:" OPTION; do
     
-       case "$OPTION" in
-               h)
-                       usage
-                       exit
-                       ;;
-               c)
-                       CMD=$OPTARG
-                       ;;
-       esac
+  case "${OPTION}" in
+    h)
+      usage
+      exit
+      ;;
+    v)
+      VERBOSE=1
+      ;;
+    p)
+      PINGHOST=${OPTARG}
+      ;;
+    c)
+      CMD=${OPTARG}
+      ;;
+  esac
 done
 
-if [ -z "$CMD" ]; then
+if [ -z "${CMD}" ]; then
     echo "No command given."
     usage
     exit 2
 fi
 
-if ping -c1 8.8.8.8 2>&1 >/dev/null; then
-    $CMD
+if [ -z "$(ip r list exact default)" ]; then
+  if [ "1" -eq "${VERBOSE}" ];  then
+    echo "Not online because no default route."
+  fi
+  exit
+fi
+
+
+if ! ping -c1 "${PINGHOST}" 2>&1 >/dev/null; then
+  if [ "1" -eq "${VERBOSE}" ];  then
+    echo "Not online because cannot ping ${PINGHOST}."
+  fi
+  exit
 fi
+
+${CMD}