首页 > 解决方案 > 函数中的 Bash 命令替换不会从命令替换返回返回码

问题描述

我发现在函数中,使用命令替换将命令输出放入变量中,使用 $? 从命令替换中获取退出代码返回 0,而不是返回的代码。

当不在函数中时,命令替换按预期返回返回码。

我想访问返回的文本和返回码。我知道一种解决方法是将输出重定向到文件,然后将文件转换为变量。我想避免使用文件。

我在网上找不到任何帮助。

有什么想法吗?

bash 脚本演示了这一点:

#!/bin/bash
# 20210511
# return_test.sh
# test of return code within a function

declare -rx this_script=${0##*/}

function return_1 () {
    
    echo "returned text"
    return 1

} # function return_1

function return_test () {
    
    local return_value=$`return_1`
    echo "return 1 \`\`   code = $?"
    echo $return_value
    local return_value=$(return_1)
    echo "return 1 ()   code = $?"
    echo $return_value
    local return_value=$( (return_1) )
    echo "return 1 (()) code = $?"
    echo $return_value
    return_1
    echo "return 1      code = $?"


} # function return_test

echo ""
echo "Starting $this_script"
echo "Test of return codes from a command substituted function called with a function"
echo
return_test
echo
echo "Test not in a function"
return_value=$(return_1)
echo "return 1 ()   code = $?"
echo $return_value
echo
exit

输出:

$ ./return_test.sh

Starting return_test.sh
Test of return codes from a command substituted function called with a function

return 1 ``   code = 0

$returned text

return 1 ()   code = 0

returned text

return 1 (()) code = 0

returned text

returned text

return 1      code = 1

Test not in a function

return 1 ()   code = 1

returned text

标签: bashfunctionreturn-valuecommand-substitutionreturn-code

解决方案


推荐阅读