bash - Bash:如何使用局部变量同时捕获错误和回显值?
问题描述
当我试图捕获 shellscript 中的错误时,如果我使用局部变量来捕获回显值,$? 即使函数返回 1,捕获返回值也始终为 0。
这是为什么?
我可以使用全局变量来解决这个问题,但我猜它违反了标准。当我想捕获一些回声值时,是否有更好的方法来处理错误?
谢谢!
例如:
使用局部变量时:
test_error_handle() {
echo "Some text"
return 1
}
method() {
local test=$(test_error_handle) # Use local variable
echo "$?"
echo ${test}
}
method
输出:
0
Some text
使用全局变量时:
test_error_handle() {
echo "Some text"
return 1
}
method() {
test=$(test_error_handle) # Use local variable
echo "$?"
echo ${test}
}
method
输出:
1
Some text
解决方案
通常退出状态是最后执行的命令的退出状态。
local test=$(test_error_handle)
这里发生的是:
- 外壳运行命令
test_error_handle
- 然后shell运行命令
local
local
以零退出状态返回
因此,当echo $?
您看到local
命令的退出状态时。
当你这样做时:
test=$(test_error_handle)
此表达式的退出状态是运行的命令替换的退出状态test_error_handle
。
推荐阅读
- dataset - 将鼠标悬停在 Chart.js 中活动其他数据集的折线图数据上
- c++ - 特征稀疏矩阵。关于行对非零元素进行排序
- angular - 复制选项卡时未清除会话存储
- grafana - 无法通过 grafana HTTP API 导入 grafana 仪表板
- pip - pip 安装错误命令“python setup.py egg_info”失败,错误代码为 1
- c# - WPF 附加属性的类型被框架破坏
- angular - Angular:从文件中获取预取工厂函数参数
- python - Airflow jinja2 模板化 json 文件
- angular - 我试图将值从一个包含对象的数组推送到另一个包含对象的数组
- python - keras中model.compile的参数'weighted_metrics'和model.fit_generator的参数'class_weight'之间的区别?