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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 00:47:19  来源:igfitidea点击:

Bash: let statement vs assignment

linuxbashunix

提问by IDDQD

What is the difference between assigning to a variable like var=fooand using let like let var=foo? Or cases like var=${var}barand 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.

letdoes exactly what (( ))do, it is for arithmetic expressions. There is almost no differencebetween letand (( )).

let确实做什么(( )),它用于算术表达式。目前几乎没有差别之间let(( ))

Your examples are invalid. var=${var}baris going to add word barto the varvariable (which is a string operation), let var+=baris not going to work, because it is not an arithmetic expression:

你的例子无效。var=${var}bar要将单词添加barvar变量(这是一个字符串操作),let var+=bar是行不通的,因为它不是算术表达式:

$ var='5'; let var+=bar; echo "$var"
5

Actually, it IS an arithmetic expression, if only variable barwas set, otherwise baris treated as zero.

实际上,它是一个算术表达式,如果只bar设置了变量,否则bar视为零。

$ var='5'; bar=2; let var+=bar; echo "$var"
7