问题描述
我发现在函数中,使用命令替换将命令输出放入变量中,使用 $?从命令替换中获取退出代码返回 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
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)