bash脚本 - 如果在函数中选中,则退出上一个命令的状态

use*_*330 2 bash shell

我不明白 - 如果我检查函数中的命令的退出状态并存储在局部变量中,我总是得到答案0.从函数外部,我得到正确的退出状态.

#!/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"
Run Code Online (Sandbox Code Playgroud)

输出是:

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
Run Code Online (Sandbox Code Playgroud)

4的状态是正确的.

cam*_*amh 7

local命令service mysql status在函数中的命令之后运行.它正在返回0.您正在丢失service命令的返回状态.

local声明分为两部分:

local output
local mysql_status

output=`service mysql status`
mysql_status=$?
Run Code Online (Sandbox Code Playgroud)