bash 中是否有带赋值(三元条件)的内联if?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14106679/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there an inline-if with assignment (ternary conditional) in bash?
提问by IQAndreas
Possible Duplicate:
Ternary operator (?:) in Bash
可能的重复:
Bash 中的三元运算符 (?:)
If this were AS3 or Java, I would do the following:
如果这是 AS3 或 Java,我会执行以下操作:
fileName = dirName + "/" + (useDefault ? defaultName : customName) + ".txt";
But in shell, that seems needlessly complicated, requiring several lines of code, as well as quite a bit of repeated code.
但在 shell 中,这似乎是不必要的复杂,需要几行代码,以及相当多的重复代码。
if [ $useDefault ]; then
fileName="$dirName/$defaultName.txt"
else
fileName="$dirName/$customName.txt"
fi
You could compress that all into one line, but that sacrifices clarity immensely.
您可以将所有内容压缩为一行,但这会极大地牺牲清晰度。
Is there any better way of writing an inline ifwith variable assignment in shell?
有没有更好的方法if在 shell中编写带有变量赋值的内联?
回答by William Pursell
Just write:
写就好了:
fileName=${customName:-$defaultName}.txt
It's not quite the same as what you have, since it does not check useDefault. Instead, it just checks if customNameis set. Instead of setting useDefaultwhen you want to use the default, you simply unset customName.
它与您拥有的并不完全相同,因为它不检查useDefault. 相反,它只是检查是否customName设置。无需设置useDefault何时要使用默认值,只需 unset customName。
回答by Keith Thompson
There is no ?:conditional operator in the shell, but you could make the code a little less redundant like this:
?:shell 中没有条件运算符,但是您可以像这样使代码不那么冗余:
if [ $useDefault ]; then
tmpname="$defaultName"
else
tmpname="$customName"
fi
fileName="$dirName/$tmpname.txt"
Or you could write your own shell function that acts like the ?:operator:
或者您可以编写自己的 shell 函数,其作用类似于?:运算符:
cond() {
if [ "" ] ; then
echo ""
else
echo ""
fi
}
fileName="$dirname/$(cond "$useDefault" "$defaultName" "$customName").txt"
though that's probably overkill (and it evaluates all three arguments).
尽管这可能有点矫枉过正(并且它评估了所有三个参数)。
Thanks to Gordon Davisson for pointing out in comments that quotes nest within $(...).
感谢 Gordon Davisson 在评论中指出嵌套在$(...).

