Hi all
I'm trying to evalute the return status of a function without much success. I've put a very basic example below to explain.
check_ok() works fine but when used within an if statement, it always returns true, whether it is true or false. I'm guessing it returns true as the function succeeded, rather than the statement within it.
The check_ok function I am actually using has a lot of code ans is used many times in the script. I have tried various ways using $?/return etc but was hoping someone could explain the correct way to do this?
thanks for any help.
check_ok()
{
ps aux | grep -v grep | grep SOMETHING
}
if [[ check_ok ]]
then
echo OK
fi
Without seeing the actual check_ok() it would be a little difficult to say exactly what your problem is. Unless you put in an explicit return statement, the routine will return the value of the last expression evaluated. If it always returns true then it would imply that the last expression in the subroutine either always returns true or has, coincidentally, always returned true in the cases you've tested.
The function is really just a long series of greps.
I have tried to return $? and then check check_ok !=0 but this errors and I dont know how to check for the return status correcly?
check_ok()
{
ps aux | grep -v grep | grep SOMETHING
return $?
}
if [[ check_ok !=0 ]]
then
echo not running
fi
Here's just a stupid snippet to check return values. Should print
TRUE
NOT TRUE
when executed. If you wanted to test for not true, you could use -ne instead of -eq.
#!/usr/bin/ksh
return_true () {
return 0
}
return_not_true () {
return 1
}
return_true
if [[ $? -eq 0 ]]
then
echo "TRUE"
else
echo "NOT TRUE"
fi
return_not_true
if [[ $? -eq 0 ]]
then
echo "TRUE"
else
echo "NOT TRUE"
fi
The return value of cmd | cmd1 | cmd2 is whatever cmd2 returns.
You can use grep -q <pattern> to suppress any out. It returns either > 0 (failure) or 0 = success (pattern found).
Long series of grep <> |grep <> | grep <> ... eat your system for lunch, if you get my drift.