在批处理文件中定义和使用变量

本文探讨了在批处理文件中定义和使用变量时遇到的问题,指出空格和引号在变量名和值中的重要性。错误地包含空格可能导致变量未正确回显。解决方案包括删除定义中的额外空格或使用特定语法来包含或避免引号。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自: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" "

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值