简体   繁体   English

shell 脚本中的变量赋值约定

[英]Variable assignment convention in shell scripts

In bash script it seems to not allow a space on either side of the = sign.在 bash 脚本中, =号的两边似乎都不允许有空格。 For example:例如:

# bad
a= "ok"
# bad
a ="ok"
# bad
a = "ok"
# good
a="ok"

Is this the same across all shell languages, or bash-specific?这在所有shell种语言中都是一样的,还是特定于 bash 的? Out of curiosity, why does it not allow a space next to the assignment operator?出于好奇,为什么赋值运算符旁边不允许有空格?

For specific shells, you'll need to look up the documentation for that shell. For bash , it's a requirement that there be no spaces in that form (note that there are no spaces on either side of the = ):对于特定的 shell,您需要查找 shell 的文档。对于bash ,要求该形式中没有空格(请注意=的两边都没有空格):

A variable may be assigned to by a statement of the form name=[value] .变量可以通过name=[value]形式的语句赋值。

One reason why this may be the case is that you can use command-temporal assignments where a variable is set only for the duration of a command:出现这种情况的原因之一是您可以使用命令时态赋值,其中变量仅在命令执行期间设置:

pax:~> x=314159 ; echo $x
314159
pax:~> x=42 bash -c 'echo $x'
42
pax:~> echo $x
314159

Allowing spaces in the assignment would make it a little difficult to figure out where the assignment finished and where the command started.在作业中留有空格会使弄清楚作业在哪里结束以及命令从哪里开始变得有点困难。 For example:例如:

x= echo echo hello

Should this set x to echo then run echo hello or should it set x to "" and then run echo echo hello ?这应该将x设置为echo然后运行echo hello还是应该将x设置为""然后运行echo echo hello

If you want your assignment to be nicely formatted with spaces, you can use the ((...)) arithmetic evaluation:如果你想让你的作业很好地用空格格式化,你可以使用((...))算术评估:

pax:~> (( val = 117 / 3 )) ; echo $val
39

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

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