问题描述
批处理文件存在以下问题.我简化了下面的问题.
I have the following problem with batch files. I simplify the problem below.
运行以下批处理文件foo.bat,以标准输出(在本例中为命令提示符窗口)而不是hey
的形式返回word
.
Running the following batch file, foo.bat, returns word
in standard out (in this case, command prompt window) instead of hey
.
@SET 1word="hey"
@ECHO %1word%
但是,从命令行执行echo %1word%
会返回hey
.
However, executing echo %1word%
from the command line returns hey
.
是否有理由/应该是这种情况?不允许数字作为环境变量名称的前缀吗?
Is there a reason this should/might be the case? Are numbers not allowed to prefix environment variable names?
推荐答案
您可以创建和使用名称以数字开头的环境变量 ,但这不是一个好主意,应避免使用 .定义变量没有问题.但是使用正常的百分比扩展进行扩展是个问题.
You can create and use environment variables with names that begin with a digit, but it is not a good idea, and should be avoided. Defining the variable is no problem. But expansion using normal percent expansion is a problem.
问题是批处理解析器在%1word%
中看到了首字母%1
,并扩展了第一个参数而不是变量.即使未传递任何参数,它仍会将不存在的第一个参数扩展为空字符串.在 https://stackoverflow.com/a/4095133/1012053 和https://stackoverflow.com/a/7970912/1012053 .
The problem is the batch parser sees the inital %1
in %1word%
and expands the first argument instead of the variable. Even if no argument was passed, it still expands the non-existent first argument into an empty string. The rules are explained at https://stackoverflow.com/a/4095133/1012053 and https://stackoverflow.com/a/7970912/1012053.
您可以使用延迟扩展来访问变量.
You can access the variable using delayed expansion instead.
这是一个演示问题的示例脚本:
Here is an example script that demonstrates the issues:
@echo off
setlocal enableDelayedExpansion
set "1var=Environment variable value."
call :test "Argument 1 value"
exit /b
:test
echo arg 1 = %1
echo 1var normal = %1var%
echo 1var delayed = !1var!
-样本输出-
arg 1 = "Argument 1 value"
1var normal = "Argument 1 value"var
1var delayed = Environment variable value.
请注意,形式为%1
的参数扩展仅是批处理脚本中的一个问题-与在命令提示符(非批处理)上下文中发出的命令无关.因此,您可以在命令提示符下定义1个单词,然后echo %1word%
在命令提示符下可以正常工作.
Note that argument expansion of the form %1
is only an issue within a batch script - it is not relevant to commands issued in a command prompt (non batch) context. So you could define 1word from the command prompt and then echo %1word%
would work fine from the command prompt.
由于复杂性,故事的寓意是-不要使用以数字开头的变量名".
Because of the complexities, the moral of the story is - "don't use variable names that begin with a digit".
这篇关于有效的批处理文件变量名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!