简体   繁体   English

:=和[[之间有行为差异吗?

[英]Are there behavioral differences between := and [[?

Do these two code snippets, one using the colon equal notation, and the other using the double bracket program exhibit the same behavior? 这两个代码片段是否都表现出相同的行为,一个使用冒号等号,另一个使用双括号程序?

: "${foo:=bar}"

and

if ! [[ $foo ]]; then
    foo=bar
fi

If they are the same in behavior, then which one is preferred stylistically? 如果它们的行为相同,那么从造型上看,哪个是首选? I've seen both of these used in various places and I can't decide which one is better for maintainability and readability. 我已经看到这两种方法在不同的地方使用过,因此我无法确定哪种方法在可维护性和可读性上更好。

As far as I'm aware, they're functionally equivalent. 据我所知,它们在功能上是等效的。 As for which is best, I'd say that's a matter of taste. 至于哪个最好,我想说这是一个品味问题。 Personally I'd prefer : ${foo:=bar} as it's more concise but others less familiar with the syntax would probably go for the more obvious approach. 就个人而言,我更喜欢: ${foo:=bar}因为它更简洁,但其他人对语法的不熟悉可能会采用更明显的方法。

Note that your first approach uses standard shell features, so should work on any POSIX-compliant shell. 请注意,您的第一种方法使用标准外壳程序功能,因此应在任何符合POSIX的外壳程序上工作。 To make your second approach more portable, I'd go with: 为了使您的第二种方法更具可移植性,我将采用:

if [ -z "$foo" ]; then
    foo=bar
fi

As suggested in the comments, another option which could be seen as a compromise between clarity and brevity would be: 如评论中所建议,可以将另一种选择视为清晰与简洁之间的折衷方案:

foo=${foo:-bar}

${foo:-bar} evaluates to $foo if it's already set, else bar . 如果已设置${foo:-bar} ,则其值为$foo ,否则为bar

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

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