#!/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
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}