user3441151 user3441151 - 3 months ago 35
Bash Question

centos 7 -eq: unary operator expected

I have to check Tomcat 8 is running or not. For this i am using the below script.

#!/bin/bash

statuscode=$(wget --server-response http://localhost:8080 2>&1 | awk '/^ HTTP/{print $2}')

if [ $statuscode -eq 200 ]
then
echo "TOMCAT OK"
exit 0
else
echo "TOMCAT CRITICAL"
exit 2
fi


When I run this script on CentOS 7.

If Tomcat 8 is running then script is running without any error.

If Tomcat 8 is stopped then script is running with following error

line 5: [: -eq: unary operator expected


Please help me to fix this issue.

Answer

Check if the variable is not empty before comparing it against the expected output.

#!/bin/bash

statuscode=$(wget --server-response http://localhost:8080 2>&1 | awk '/^  HTTP/{print $2}')

if [ -n "$statuscode" ] && [ $statuscode -eq 200 ]
then
    echo "TOMCAT OK"
    exit 0
else
    echo "TOMCAT CRITICAL"
    exit 2
fi
Comments