我一直在這一點上敲我的頭。想看看我做錯了什麼,這可能是我的一切。我正在ping一個IP,然後當它發生故障時,它會發送一個通知。我的問題是與getops。我用它來試圖解析電子郵件地址和IP。這些都不被解析。我該如何去解析我的兩個變量使用getopts我需要讓我的腳本正常運行。預先感謝您:)bash getops沒有通過電子郵件或IP地址
#!/bin/bash
# Variable(s)
# --------
EMAIL_DOWN_SENT="0";
EMAIL_UP_SENT="0";
PING_FAILED="0";
PING_UP_AGAIN="0";
# FUNctions
# ---------
#
# Echo a string value that is passed
echo_text() {
echo -e >&2 "[email protected]";
}
echo_help() {
echo_text "Usage: $(basename "$0") [-e] [EMAIL][-h] [-i] [IP]\n\nScript to ping ip address to see if it's up and send an alert on status changes.\n
-e Enter email: [email protected]
-h This help screen
-i IP to ping";
exit;
}
# Main body
# ---------
#
# Get command line options
# ------------------------
while getopts ":e:hi:" OPTIONS
do
case $OPTIONS in
e) EMAIL=$OPTARGS ;;
h|\?) echo_help ;;
i) IP= $OPTARGS | grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'; if [ "$?" != "0" ]; then echo_text "Please enter a valid IP"; exit 1; fi; ;;
*) echo_text "$OPTARGS is invalid, try again";
exit 1 ;;
esac
shift $((OPTIND-1))
done
echo_text "Your email is: $EMAIL";
echo_text "Your ip to ping is: $IP";
# Ping me
# -------
trap "echo You hit ctrl-c, now exiting..; exit" SIGINT
while :
do
ping -i 2 -c 2 $IP > /dev/null
if [ $? -ne 0 ]; then
let PING_DOWN+=1
echo_text "Down! Abandon all hope who enter here...";
PING_FAILED="1";
# If greater than 3 cycles send an email...
if [[ $PING_DOWN -ge 3 && $EMAIL_DOWN_SENT -eq 0 ]]; then
echo "$IP Down!"|mutt -s "Ping Failed!" $EMAIL;
EMAIL_DOWN_SENT="1";
fi
else
let PING_UP+=1
echo_text "Up! Ahoy! Host alive!";
# If greater than 3 cycles send an email...
if [[ $PING_UP -ge 3 && $EMAIL_UP_SENT -eq 0 && $PING_FAILED -eq 1 ]]; then
echo "$IP up!"|mutt -s "Ping succeeded!" $EMAIL;
EMAIL_UP_SENT="1";
PING_UP_AGAIN="1";
fi
# Reset checks
if [ $PING_UP_AGAIN -eq 1 ]; then
PING_FAILED="0";
PING_UP="0";
PING_DOWN="0";
EMAIL_UP_SENT="0";
EMAIL_DOWN_SENT="0";
fi
fi
done
if [ ! `echo "$OPTARG" | grep -qE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'` ]; then
echo_text "Please enter a valid IP"
exit 1
fi
IP="$OPTARG"
解析,不通過。 – paxdiablo 2013-04-21 07:35:54
謝謝,修正了錯誤的語法 – dasunsrule32 2013-04-21 08:14:58