Current File : //usr/local/keyhelp/call_url |
#!/bin/bash
#
# _ __ _ _ _ (R)
# | |/ /___ _ _| |_| |___| |___
# | | / -_) |_/ | _ | -_) | _ \
# |_|\_\___|\__, |_| |_|___|_| _/
# |___/ |_|
#
# @author Alexander Mahr <am@keyweb.de>
# @link https://www.keyhelp.de
#
#
# This script calls a URL and checks if the returned HTTP status code is 200.
# It is supposed to be used with KeyHelp's 'Scheduled Tasks' feature.
#
VERSION="1.1"
DEBUG=0
#=======================================================================================================================
# Functions
#=======================================================================================================================
function usage()
{
THIS_FILENAME=`basename "$0"`
echo "Calls a URL and checks if the returned HTTP status code is 200."
echo "This script is quiet by default if no errors occur, as it is supposed to be used as a cron script."
echo ""
echo "Usage: $THIS_FILENAME [options...] <URL>"
echo ""
echo "Options:"
echo "-h, --help Displays this help text."
echo "-d, --debug Enables debug outputs."
echo "-v, --version Shows the script version."
}
function echo_error()
{
echo $1 >&2;
}
function echo_debug()
{
if [ $DEBUG == "1" ]; then
echo $1;
fi
}
#=======================================================================================================================
# Parse parameters
#=======================================================================================================================
POSITIONAL=()
# Options
while [[ $# -gt 0 ]]
do
KEY="$1"
case $KEY in
-h|--help)
usage
exit 0
;;
-d|--debug)
DEBUG=1
shift
;;
-v|--version)
echo $VERSION
exit 0
;;
-*)
echo_error "Error | Unknown option: $1"
exit 1
;;
*)
# Positional parameter, save it in an array for later
POSITIONAL+=($KEY)
shift
;;
esac
done
# Restore positional parameters
set -- "${POSITIONAL[@]}"
# Assign positional parameter
URL="$1"
#=======================================================================================================================
# Call URL
#=======================================================================================================================
if [ -z $URL ]; then
echo_error "URL is missing."
exit 1
fi
HTTP_CODE=`curl --silent --show-error --location --insecure --output "/dev/null" --write-out "%{http_code}" "$URL"`
if [ $? -ne 0 ]; then
echo_error "Failed to call URL: $1"
exit 1
fi
if [[ "$HTTP_CODE" -lt 200 || "$HTTP_CODE" -ge 300 ]]; then
echo_error "URL called: $1"
echo_error "Status: $HTTP_CODE"
exit 1
fi
echo_debug "URL called: $1"
echo_debug "Status: $HTTP_CODE"