简体   繁体   English

bash脚本-如果在函数中选中,则先前命令的退出状态会有所不同

[英]bash script - exit status of previous command different if checked in a function

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. 我不明白这一点-如果我检查函数中命令的退出状态并将其存储在局部变量中,则总是得到答案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"

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. 状态4是正确的。

The local command is run after the service mysql status command in your function. local命令在函数中的service mysql status命令之后运行。 It is that which is returning 0. You are losing the return status of the service command. 就是返回0的那个。您正在丢失service命令的返回状态。

Split the local statement into two: local语句分成两个部分:

local output
local mysql_status

output=`service mysql status`
mysql_status=$?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM