本文翻译自:Defining and using a variable in batch file
I'm trying to define and use a variable in a batch file. 我正在尝试在批处理文件中定义和使用变量。 It looks like it should be simple: 看起来应该很简单:
@echo off
set location = "bob"
echo We're working with "%location%"
The output I get is the following: 我得到的输出如下:
We're working with ""
What's going on here? 这里发生了什么? Why is my variable not being echo'd? 为什么我的变量没有被回显?
#1楼
参考:https://stackoom.com/question/iHGe/在批处理文件中定义和使用变量
#2楼
The space before the =
is interpreted as part of the name, and the space after it (as well as the quotation marks) are interpreted as part of the value. =
之前的空格被解释为名称的一部分,而其后面的空格(以及引号)被解释为值的一部分。 So the variable you've created can be referenced with %location %
. 因此,您创建的变量可以用%location %
引用。 If that's not what you want, remove the extra space(s) in the definition. 如果这不是您想要的,请删除定义中的多余空间。
#3楼
The spaces are significant. 空间很大。 You created a variable named 'location '
with a value of 您创建了一个名为'location '
的变量,其值为 ' "bob"'
. ' "bob"'
。 Note - enclosing single quotes were added to show location of space. 注意-添加了单引号以显示空间位置。
If you want quotes in your value, then your code should look like 如果要在值中加上引号,则代码应如下所示
set location="bob"
If you don't want quotes, then your code should look like 如果您不想使用引号,那么您的代码应如下所示
set location=bob
Or better yet 还是更好
set "location=bob"
The last syntax prevents inadvertent trailing spaces from getting in the value, and also protects against special characters like &
|
最后一种语法可防止无意中使用尾随空格来获取值,还可以防止特殊字符(例如&
|
etc. 等等
#4楼
input location.bat
输入location.bat
@echo off
cls
set /p "location"="bob"
echo We're working with %location%
pause
output 输出
We're working with bob
(mistakes u done : space
and " "
) (您所做的错误: space
和" "
)