Linux Bash:让语句与赋值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18704857/
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
Bash: let statement vs assignment
提问by IDDQD
What is the difference between assigning to a variable like var=foo
and using let like let var=foo
? Or cases like var=${var}bar
and let var+=bar
? What are the advantages and disadvantages of each approach?
分配给变量 likevar=foo
和使用 let like之间有什么区别let var=foo
?或者像var=${var}bar
和这样的情况let var+=bar
?每种方法的优缺点是什么?
采纳答案by Aleks-Daniel Jakimenko-A.
let
does exactly what (( ))
do, it is for arithmetic expressions. There is almost no differencebetween let
and (( ))
.
let
确实做什么(( ))
,它用于算术表达式。目前几乎没有差别之间let
和(( ))
。
Your examples are invalid. var=${var}bar
is going to add word bar
to the var
variable (which is a string operation), let var+=bar
is not going to work, because it is not an arithmetic expression:
你的例子无效。var=${var}bar
要将单词添加bar
到var
变量(这是一个字符串操作),let var+=bar
是行不通的,因为它不是算术表达式:
$ var='5'; let var+=bar; echo "$var"
5
Actually, it IS an arithmetic expression, if only variable bar
was set, otherwise bar
is treated as zero.
实际上,它是一个算术表达式,如果只bar
设置了变量,否则bar
视为零。
$ var='5'; bar=2; let var+=bar; echo "$var"
7