#!/bin/sh set -e usage() { 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 $0 -c "echo 'online'" 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 "hvc:p:" OPTION; do case "${OPTION}" in h) usage exit ;; v) VERBOSE=1 ;; p) PINGHOST=${OPTARG} ;; c) CMD=${OPTARG} ;; esac done if [ -z "${CMD}" ]; then echo "No command given." usage exit 2 fi 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}