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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:48:29  来源:igfitidea点击:

Assignment of variables with space after the (=) sign?

bashshellsh

提问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/pwdcontaining 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 PWDis 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, band care read correctly. After this line, IFSreturns to the default value, so the rest of the script isn't affected.

这将字段分隔符设置为逗号,以便正确读取a,bc。在此行之后,IFS返回到默认值,因此脚本的其余部分不受影响。

Perhaps on some systems, the output of the command pwdis affected by the value of the variable PWD, so doing this prevents problems caused by PWDbeing 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/pwdto PWD.

我们将分配/bin/pwdPWD.

But

PWD= /bin/pwd

means that we call /bin/pwdwith PWDset to the empty string. This assignment only affects the sub process, not the current one.

意味着我们调用/bin/pwdwithPWD设置为空字符串。此分配仅影响子进程,而不影响当前进程。

回答by tripleee

PWD= pwd

This syntax assigns the empty value to the variable PWDfor the duration of the pwdcommand.

此语法PWDpwd命令的持续时间内将空值分配给变量。

PWD=ick
echo "$PWD"

This assigns PWDfor the remainder of the script.

这分配给PWD脚本的其余部分。

PWD=ick pwd
echo "$PWD"

This assigns PWDonly for the duration of the pwdcommand; the echowill echo the value which was in effect before and after the pwdinvocation.

PWD仅在pwd命令期间分配;的echo将回声这在效果之前和之后的值pwd调用。

PWD=

This simply assigns the empty value to PWD.

这只是将空值分配给PWD

Pathologically,

病理上,

PWD = ick

attempts to run the command PWDwith the arguments =and ick

尝试PWD使用参数运行命令=ick