Windows echo 命令无法回显用户设置的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1884071/
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-09 06:58:52  来源:igfitidea点击:

Windows echo command can't echo a user-set variable

windowsbatch-filecmdenvironment-variableswindows-console

提问by jacobsee

What did I do to screw up my CMD shell? Windows XP Pro, open a cmd window and do:

我做了什么来搞砸我的 CMD 外壳?Windows XP Pro,打开一个 cmd 窗口并执行:

C:\>set tt = name

C:\>set tt
tt = name

C:\>echo %tt%
%tt%

C:\>echo %time%
14:13:28.67

The echo command doesn't work for some reason. I can echo the built-in variables just fine. Tried it on another computer and that works as expected

由于某种原因,echo 命令不起作用。我可以很好地回应内置变量。在另一台电脑上试过,效果如预期

回答by akf

The setcommand does not take spaces. The proper syntax would be:

set命令不占用空格。正确的语法是:

set tt=name

What you have done in your example is set an environment variable tt<space>. With that in mind, you can try this:

您在示例中所做的是设置环境变量tt<space>。考虑到这一点,你可以试试这个:

echo %tt%

and see your output.

并查看您的输出。

回答by Eric

Have you tried setting the variable with no space between the equals? (set tt=name)

您是否尝试过在等号之间没有空格的情况下设置变量?(设置 tt=name)

回答by Franta

The most upvoted answer here, accepted far ago, claims that:

这里最受好评的答案,很久以前就被接受了,声称:

"The setcommand does not take spaces."

set命令不占用空格。”

But that is not correct: The %tt %variable actually works: It can be set and referenced. (Despite it isconfusing.)

但这不正确:该%tt %变量实际上有效:它可以被设置和引用。(尽管它混乱的。)

Problem reproduced:

问题重现:

Indeed, on my Win7:

确实,在我的 Win7 上:

C:\>set os
OS=Windows_NT

C:\>set tt = name
C:\>set tt2= name
C:\>set tt3=name
C:\>set tt
tt = name
tt2= name
tt3=name

I tried and got:

我尝试并得到:

C:\>echo "%os%"
"Windows_NT"

C:\>echo "%tt3%"
"name"
C:\>echo "%tt2%"
" name"
C:\>echo "%tt%"
"%tt%"

Resolved cases:

已解决案例:

The intuitively expected variable %tt%is not set. But %tt %is set instead:

%tt%未设置直观预期的变量。但是%tt %设置为:

C:\>echo "%tt %"
" name"

Even more, with a space at the end of the value, set tt4 = name :

更重要的是,在值的末尾有一个空格,set tt4 = name

C:\>echo "%tt4 %"
" name "

Conclusions:

结论:

The setcommand does not trim():

set命令不会trim()

  • The space before "=" is included to the var_name.
  • The space after "=" is included to the var_value.
  • The space at the end of the var_valueis included to it.
  • “=”前的空格包含在var_name.
  • “=”后的空格包含在var_value.
  • 末尾的空格var_value包含在其中。

On the other hand:

另一方面:

  • The space at the beginning of the var_nameis not included to it, which is rather normal for command line arguments in general.
  • 开头的空格var_name不包括在内,这对于一般的命令行参数来说是很正常的。