I don’t get this – if I check the exit status of a command in a function and store in a local variable, I always get the answer 0. From outside the function, I get the correct exit status.
#!/bin/bash
function check_mysql()
{
local output=`service mysql status`
local mysql_status=$?
echo "local output=$output"
echo "local status=$mysql_status"
}
check_mysql
g_output=`service mysql status`
g_mysql_status=$?
echo "g output=$g_output"
echo "g status=$g_mysql_status"
Output is:
local output=MySQL is running but PID file could not be found..failed
local status=0
g output=MySQL is running but PID file could not be found..failed
g status=4
The status of 4 is the correct one.
The
localcommand is run after theservice mysql statuscommand in your function. It is that which is returning 0. You are losing the return status of theservicecommand.Split the
localstatement into two: