CentOS 7 -eq:预期的一元运算符

CentOS 7 -eq: unary operator expected

我必须检查 Tomcat 8 是否 运行ning。为此,我使用以下脚本。

#!/bin/bash

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

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

当我 运行 这个脚本在 CentOS 7.

如果 Tomcat 8 是 运行ning 那么脚本是 运行out 任何错误。

如果 Tomcat 8 停止,则脚本 运行 出现错误

line 5: [: -eq: unary operator expected

我该如何解决这个问题?

在将变量与预期输出进行比较之前检查变量是否不为空。

#!/bin/bash

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

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

试试这个:

如果statuscode为空,则抛出-eq: unary operator expected.

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

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