0

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?

fuzzybear3965
  • 243
  • 5
  • 15

3 Answers3

6

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".

Community
  • 1
  • 1
dbenham
  • 127,446
  • 28
  • 251
  • 390
3

%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
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • This was good, but I liked the information dbenham added regarding what was happening to allow the variable to be parsed correctly in the command line and how I might fix the batch file using delayed expansion. – fuzzybear3965 May 09 '15 at 13:57
1

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

Carl Gueck
  • 31
  • 3