简体   繁体   English

声明具有进程替换的变量时,能否捕获子外壳程序的退出代码?

[英]Can the exit code of a subshell be captured when declaring a variable with process substitution?

Assume set -e is active for all that follows. 假设set -e对于随后的所有活动都是活动的。

This will exit non-zero: 这将退出非零值:

x=$(false)

But, none of these will exit non-zero: 但是,这些都不会退出非零值:

declare x=$(false)
readonly x=$(false)
local x=$(false)

If you want to declare a mutable variable you can just do x=$(false) . 如果要声明一个可变变量,可以执行x=$(false) But if you want a readonly variable you have to resort to something like this: x=$(false) ; readonly x 但是,如果您想要一个只读变量,则必须诉诸如下代码: x=$(false) ; readonly x x=$(false) ; readonly x

However, if you are in a function and you want a local, readonly variable you cannot do 但是,如果您在函数中,并且想要局部只读变量,则无法执行

x=$(false) ; local -r x

since you will overwrite the global x. 因为您将覆盖全局x。

You could do local x=$(false) and the try to inspect x manually to see if there was an error. 您可以执行local x=$(false)并尝试手动检查x以查看是否存在错误。 Or, you might check for output on stderr. 或者,您可以检查stderr上的输出。 But, neither of these will work in all cases; 但是,这些都不在所有情况下都有效。 and, they're cumbersome. 而且,它们很麻烦。

Is there any way to get the exit code from a process substitution when assigning the result? 分配结果时,有什么方法可以从流程替换中获取退出代码?

To check the status of the process substitution, the assignment must be the only thing performed by the statement. 要检查流程替换的状态,赋值必须是语句执行的唯一操作。 In a statement such as local x=$(false) , the value returned is the status of local, which typically succeeds. 在诸如local x=$(false)类的语句中,返回的值是local的状态,通常会成功。 To create a local readonly variable in a function and check the assignment from a process substitution, you can do: 要在函数中创建局部只读变量并检查来自进程替换的分配,您可以执行以下操作:

local x
x=$(false) || echo "assigment of x failed !!" >&2
readonly x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM