2012-05-01 21 views
2

我不明白 - 如果我检查某个函数中的命令的退出状态并存储在局部变量中,我总是得到答案0。从功能外,我可以得到正确的退出状态。bash脚本 - 退出前一个命令的状态不同,如果在函数中检查

#!/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" 

输出是:

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 

4的状态是正确的。

回答

7

local命令在您的函数中的service mysql status命令之后运行。正是那个返回0.你正在失去service命令的返回状态。

斯普利特local声明为两个:

local output 
local mysql_status 

output=`service mysql status` 
mysql_status=$? 
+0

完美 - 谢谢。 – user265330

相关问题