问题
I have the following problem with batch files. I simplify the problem below.
Running the following batch file, foo.bat, returns word
in standard out (in this case, command prompt window) instead of hey
.
foo.bat
@SET 1word="hey"
@ECHO %1word%
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?
回答1:
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.
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!
-- Sample Output --
arg 1 = "Argument 1 value"
1var normal = "Argument 1 value"var
1var delayed = Environment variable value.
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".
回答2:
%0
through %9
are reserved for use in batch files by the Windows command processor. They represent parameters received via the command line. This means that variables cannot start with a number.
You can test this with a simple batch file:
::foo.bat
@echo %0 %1 %2
Call it like:
C:\Test>foo Param1 Param2
Output:
C:\Test>foo Param1 Param2
C:\Test\foo.bat Param1 Param2
回答3:
in batch files, %1 is the first parameter passed, so executing ./foo.bat hello would likely print
helloword
try executing the batch file with a parameter to see if that's your problem
来源:https://stackoverflow.com/questions/30109655/valid-batch-file-variable-names