Reputation: 61
I am new to Bash programming and probably being really silly.
Basically I am writing a piece of script that will ping an IP Address I pass in, it will take from it packets transmitted and return an error or a pass message depending on the number of packets lost.
However whenever I run the script from my terminal I keep getting message -
./ipGatewayCheck.sh: line 13: [: missing
]'`
This is my code:
#!/bin/bash
healthy_status=0
warning_status=10
critical_status=100
for gateway in $@
do
RESULT=`ping -q -c 10 $gateway | grep 'packets transmitted' | awk '{print $6}' | tr -d "%"`
echo "$RESULT"
if [ $RESULT -eq $healthy_status ]; then
echo "No Issue - IP Address is pinging"
elif [ $RESULT -ge $warning_status && -le $critical_status ]; then
echo "Warning - Issue with packet loss on this IP Address"
elif [ $RESULT -eq $critical_status ]; then
echo "Critical - 100% packet loss on this IP Address"
fi
done
Any help would be greatly appreciated.
Upvotes: 2
Views: 1165
Reputation: 754280
As diagnosed by anubhava in his answer, the problem is that the &&
operator terminates the test command leaving you with a [
without a matching ]
and the error message you get.
There's an alternative fix — more traditional shell coding and portable to shells other than Bash.
If you wish to use [
, you have to use either the -a
conjunction (instead of &&
), or use two separate tests:
elif [ "$RESULT" -ge $warning_status -a "$RESULT" -le "$critical_status" ]; then
elif [ "$RESULT" -ge $warning_status ] && [ "$RESULT" -le "$critical_status" ]; then
Note that I had to add the second "$RESULT"
; I also enclosed the variables inside double quotes to make sure there are no mishaps.
Upvotes: 3
Reputation: 785376
You need to use [[
and ]]
in order to use &&
inside square brackets:
if [[ "$RESULT" -eq "$healthy_status" ]]; then
echo "No Issue - IP Address is pinging"
elif [[ "$RESULT" -ge "$warning_status" && "$RESULT" -le "$critical_status" ]]; then
echo "Warning - Issue with packet loss on this IP Address"
elif [[ "$RESULT" -eq "$critical_status" ]]; then
echo "Critical - 100% packet loss on this IP Address"
fi
Alternatively you can also use ((
and ))
in BASH:
if (( RESULT == healthy_status )); then
echo "No Issue - IP Address is pinging"
elif (( RESULT == warning_status && RESULT < critical_status )); then
echo "Warning - Issue with packet loss on this IP Address"
elif (( RESULT == critical_status )); then
echo "Critical - 100% packet loss on this IP Address"
fi
Upvotes: 5