Reputation: 461
I'm getting into the error for bash shell [: : integer expression expected"
while running below script.
#!/bin/bash
sm=$(ps -e | grep sendmail > /dev/null 2>&1)
pm=$(/etc/init.d/postfix status > /dev/null 2>&1)
check_mail(){
if [ "$sm" -eq 0 ]; then
echo "Service Status: Sendmail is Running!"
elif [ "$pm" -eq 0 ]; then
echo "Service Status: Postfix Service is Running!"
else
echo "Service Status: Both Sendmail & Postfix Service is Not Running On $(uname -n)"
fi
}
check_mail
While running the above script it's simply showing the output of
else
condition.
Service Status: Both Sendmail & Postfix Service is Not Running On host
Though, i have tested "==" rather "-eq" for comparison and [[]]
but did not worked.
Upvotes: 1
Views: 1678
Reputation: 4979
It seems to me that you are confusing the exit-status of a program with the output.var=$(command)
will put the output of command
in var
. As said in 123's comment, because you redirect everything to /dev/null
, there is no output, and therefore, sm
and pm
are empty.
If you want to see the exit status, use $?
:
#!/bin/bash
typeset -i pm
typeset -i sm
ps -e | grep sendmail > /dev/null 2>&1
sm=$?
/etc/init.d/postfix status > /dev/null 2>&1
pm=$?
check_mail(){
if [ $sm -eq 0 ]; then
echo "Service Status: Sendmail is Running!"
elif [ $pm -eq 0 ]; then
echo "Service Status: Postfix Service is Running!"
else
echo "Service Status: Both Sendmail & Postfix Service is Not Running On $(uname -n)"
fi
}
check_mail
Upvotes: 2
Reputation: 6995
I assume you are trying to assess presence of sendmail in the process list. You should change your code to this :
#!/bin/bash
check_mail(){
if
ps -e | grep sendmail > /dev/null 2>&1
then
echo "Service Status: Sendmail is Running!"
elif
/etc/init.d/postfix status > /dev/null 2>&1
then
echo "Service Status: Postfix Service is Running!"
else
echo "Service Status: Both Sendmail & Postfix Service is Not Running On $(uname -n)"
fi
}
check_mail
The reason your original code fails is that you capture the output of commands using command substitution $()
. The standard output, that is, not the exit code. Then, when using the [ -eq ]
test, which expects an integer argument (which your variable does not contain), it fails with the message you get. Since both tests always fail, the else
clause is entered.
By putting the actual commands inside the conditions of the if
statement, you are using the actual numerical return code (0
for true, non-zero for false), which is what you want here.
Upvotes: 2