在批处理⽂件中定义和使⽤变量
本⽂翻译⾃:
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楼
批处理文件怎么做#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 % . 因此,您创建的变量可以⽤
引⽤。 If that's not
因此,您创建的变量可以⽤%location %引⽤。
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和" " )

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。