bash (=) 符号后有空格的变量赋值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26971987/
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
Assignment of variables with space after the (=) sign?
提问by kaneda
In Bash, assigning values to variables is done using T=content
, with no spaces before or after the equal sign.
在 Bash 中,为变量赋值是使用 完成的T=content
,等号前后没有空格。
Despite that I've seen the following in a shell script PWD= /bin/pwd
containing a space on the right side of the equals sign.
尽管如此,我还是PWD= /bin/pwd
在等号右侧包含一个空格的 shell 脚本中看到了以下内容。
What's the purpose of it have a space?
它有一个空间的目的是什么?
采纳答案by Tom Fenech
In the example PWD= /bin/pwd
, the variable PWD
is set to the empty string before executing the command /bin/pwd
. The change only takes effect for that line.
在示例中PWD= /bin/pwd
,变量PWD
在执行命令之前被设置为空字符串/bin/pwd
。更改仅对该行生效。
This can be useful to make a temporary change to a variable for the purposes of running a command, without affecting the original value. Another example of this would be when using read
, to set a different IFS
:
这对于出于运行命令的目的对变量进行临时更改非常有用,而不会影响原始值。另一个例子是使用read
, 设置不同的IFS
:
IFS=, read a b c <<<"comma,separated,list"
This sets the field separator to a comma so that a
, b
and c
are read correctly. After this line, IFS
returns to the default value, so the rest of the script isn't affected.
这将字段分隔符设置为逗号,以便正确读取a
,b
和c
。在此行之后,IFS
返回到默认值,因此脚本的其余部分不受影响。
Perhaps on some systems, the output of the command pwd
is affected by the value of the variable PWD
, so doing this prevents problems caused by PWD
being overwritten elsewhere.
也许在某些系统上,命令的输出pwd
受变量值的影响PWD
,因此这样做可以防止因PWD
在其他地方被覆盖而导致的问题。
回答by glglgl
We are not talking about two different things here.
我们在这里不是在谈论两种不同的事情。
If we had
如果我们有
PWD=/bin/pwd
we would assign /bin/pwd
to PWD
.
我们将分配/bin/pwd
给PWD
.
But
但
PWD= /bin/pwd
means that we call /bin/pwd
with PWD
set to the empty string. This assignment only affects the sub process, not the current one.
意味着我们调用/bin/pwd
withPWD
设置为空字符串。此分配仅影响子进程,而不影响当前进程。
回答by tripleee
PWD= pwd
This syntax assigns the empty value to the variable PWD
for the duration of the pwd
command.
此语法PWD
在pwd
命令的持续时间内将空值分配给变量。
PWD=ick
echo "$PWD"
This assigns PWD
for the remainder of the script.
这分配给PWD
脚本的其余部分。
PWD=ick pwd
echo "$PWD"
This assigns PWD
only for the duration of the pwd
command; the echo
will echo the value which was in effect before and after the pwd
invocation.
这PWD
仅在pwd
命令期间分配;的echo
将回声这在效果之前和之后的值pwd
调用。
PWD=
This simply assigns the empty value to PWD
.
这只是将空值分配给PWD
。
Pathologically,
病理上,
PWD = ick
attempts to run the command PWD
with the arguments =
and ick
尝试PWD
使用参数运行命令=
和ick