From: Stefan Huber Date: Sun, 14 Jul 2019 10:20:15 +0000 (+0200) Subject: ifonline: Check for default route X-Git-Url: https://git.sthu.org/?p=shutils.git;a=commitdiff_plain;h=e7b2e754ab0f1198124536df89e468824e3ab001 ifonline: Check for default route --- diff --git a/ifonline b/ifonline index 5a26215..8bb8ae7 100755 --- 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}