bash - 函数中的 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
解决方案
推荐阅读
- amazon-web-services - Goland 没有显示 ec2 方法是否有索引器?
- sourcegraph - 使用 SourceGraph 进行更高级的搜索
- javascript - 使用 ajax 填充模式后如何再次包含我的 javascript
- scala - FS2 流到未读 InputStream
- php - PHP DateTime 对象不分配,除非调试
- c# - 从另一个命名空间调用方法并将其结果显示到来自不同命名空间的文本框
- postgresql - Postgres将jsonb值作为jsonb数组返回?
- linux - Sed:在随机文本之前插入文本
- windows - 无法从 tcl 脚本执行 NSIS 安装应用程序
- symfony - Symfony 转储服务器正在监听,但在我转储时没有听到