简体   繁体   English

bash短路一线分配

[英]assignment in bash short circuit one-liner

Can I assign a variable in a short circuit expression in bash? 我可以在bash的短路表达式中分配变量吗?

x=''
y='aaa'
( [ ! -z "$x"  ]  && (echo "using SGE ID" >&2;  num="$x") ) ||  ( [ ! -z "$y" ] && (num="z$y" && echo "trying y" ) )
echo "num : $num : $y"
exit 0

returns: 返回:

trying y
num :  : aaa

Seemingly the point of assignment is reached, but it is not evaluated, or is it in a wrong scope? 似乎已达到分配点,但尚未评估,还是在错误的范围内?

You can, but parentheses are not for grouping in the traditional sense. 可以,但是括号不是传统意义上的分组。 The commands inside parentheses run in a subshell, and any variable assignments in a subshell are local to that shell, invisible outside it. 括号内的命令在子shell中运行,并且子shell中的任何变量分配都是该shell的局部变量,在其外部不可见。

Use braces instead; 用大括号代替; note that you need a semicolon to terminate the command before a closing brace if it appears on the same line. 请注意,如果右括号出现在同一行,则需要使用分号将命令终止。

x=''
y='aaa'
{ [ ! -z "$x"  ]  && { echo "using SGE ID" >&2;  num="$x"; }; } ||
  { [ ! -z "$y" ] && { num="z$y" && echo "trying y"; }; }
echo "num : $num : $y"
exit 0

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

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