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?
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:
-- Sample Output --
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 thenecho %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".
in batch files, %1 is the first parameter passed, so executing ./foo.bat hello would likely print
try executing the batch file with a parameter to see if that's your problem
%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:
Call it like:
Output: