在bash局部变量赋值命令替换的退出code [英] exit code of command substitution in bash local variable assignment

查看:163
本文介绍了在bash局部变量赋值命令替换的退出code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何检查命令替换的退出code在bash如果任务是在一个函数的局部变量?结果
请看下面的例子。第二个是,我要检查的退出code。结果
是否有人具有良好的解决方法还是为这个正确的解决方案?

  $功能测试{测试=$(返回1);回声$ ?; };测试
1
$功能测试{本地测试=$(返回1);回声$ ?; };测试
0


解决方案

如果你看一下男子文件本地(实际上只是BASH内建手册页) ,它被视为自己的命令,这让的出口code 0 在成功创建本地变量。因此,本地被覆盖的最后一个执行的错误code。

试试这个:

 功能测试{本地测试;测试=$(返回1);回声$ ?; };测试

编辑:我继续,并试图为你,和它的作品

How can I check the exit code of a command substitution in bash if the assignment is to a local variable in a function?
Please see the following examples. The second one is where I want to check the exit code.
Does someone has a good work-around or correct solution for this?

$ function testing { test="$(return 1)"; echo $?; }; testing
1
$ function testing { local test="$(return 1)"; echo $?; }; testing
0

解决方案

If you look at the man file for local (which is actually just the BASH builtins man page), it is treated as its own command, which gives an exit code of 0 upon successfully creating the local variable. So local is overwriting the last-executed error code.

Try this:

function testing { local test; test="$(return 1)"; echo $?; }; testing

EDIT: I went ahead and tried it for you, and it works.

这篇关于在bash局部变量赋值命令替换的退出code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆