Unix Bash - 将 if/else 分配给变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29183957/
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
Unix Bash - Assign if/else to Variable
提问by space149
I have been creating to assign the output of if/else to a variable but keep on getting an error.
我一直在创建将 if/else 的输出分配给一个变量,但一直出现错误。
For Example:
例如:
mathstester=$(If [ 2 = 2 ]
Then echo equal
Else
echo "not equal"
fi)
So whenever I add $mathstester
in a script, laid out like this:
所以每当我添加$mathstester
脚本时,布局如下:
echo "Equation: $mathstester"
It should display:
它应该显示:
Equation: Equal
Do I need to lay it out differently? Is it even possible?
我需要以不同的方式布置它吗?甚至有可能吗?
回答by baky
回答by Gordon Davisson
Putting the if
statement in the assignment is rather clumsy and easy to get wrong. The more standard way to do this is to put the assignment inside the if
:
把if
语句放在赋值语句中比较笨拙,容易出错。更标准的方法是将赋值放在if
:
if [ 2 = 2 ]; then
mathstester="equal"
else
mathstester="not equal"
fi
As for testing variables, you can use something like if [ "$b" = 2 ]
(which'll do a string comparison, so for example if b is "02" it will NOT be equal to "2") or if [ "$b" -eq 2 ]
, which does numeric comparison (integers only). If you're actually using bash (not just a generic POSIX shell), you can also use if [[ "$b" -eq 2 ]]
(similar to [ ]
, but with somewhat cleaner syntax for more complicated expressions), and (( b == 2 ))
(these do numeric expressions only, and have verydifferent syntax). See BashFAQ #31: What is the difference between test, [ and [[ ?for more details.
至于测试变量,您可以使用类似的东西if [ "$b" = 2 ]
(它将进行字符串比较,例如,如果 b 是“02”,它将不等于“2”)或if [ "$b" -eq 2 ]
,它进行数字比较(仅限整数)。如果您实际上正在使用 bash(不仅仅是一个通用的 POSIX shell),您还可以使用if [[ "$b" -eq 2 ]]
(类似于[ ]
,但对于更复杂的表达式使用更简洁的语法)和(( b == 2 ))
(这些仅用于数字表达式,并且具有非常不同的语法)。请参阅BashFAQ #31: test, [ 和 [[ 之间有什么区别?更多细节。