Why won't number variables work?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SirJosh3917
Posts: 35
Joined: 02 May 2016 18:59

Why won't number variables work?

#1 Post by SirJosh3917 » 29 Nov 2016 23:41

I'm being weird only for fun in this scenario and I came across this weird thing:

Why won't this work?

Code: Select all

@set "a=@set "
%a%1=TEST
%a%b=ING
@echo %1%%b%
::The result SHOULD be "TESTING", but no, for it is only "ING"


So my question is why?
I ran into this in C# where I couldn't set a variable starting with a number.

elzooilogico
Posts: 112
Joined: 23 May 2016 15:39
Location: Spain

Re: Why won't number variables work?

#2 Post by elzooilogico » 30 Nov 2016 04:24

In batch processing there are variables with a special meaning,
%0 batch filename (or full path plus filename, if run from explorer)
%1 %2 ... %9 parameters passed to the batch file, %1 first parameter , %2 second one, and so on up to %9 nineth param.

You may access more than 9th param using shift, also %* may contain all parameters passed.
SirJosh3917 wrote:I'm being weird only for fun in this scenario and I came across this weird thing:
Why won't this work?

Code: Select all

@set "a=@set "
%a%1=TEST
%a%b=ING
@echo %1%%b%
::The result SHOULD be "TESTING", but no, for it is only "ING"

So my question is why?
I ran into this in C# where I couldn't set a variable starting with a number.

In your code @echo %1%%b% is parsed

%1
    echo the first parameter given
%%
    echo percent sign
b
    echo b
%
    single percent, echo nothing.

so output is %b

If you call your batch with a parameter (say hello), the output will be hello%b

You can set and echo number variables, though is not good practice as it may be confusing.

See

Code: Select all

setlocal enabledelayedexpansion
@set "a=@set "
%a%1=TEST
%a%b=ING
@echo %1%%b% & rem echo %b
@echo !1!%b% & echo TESTING
@echo !1!!b! & echo TESTING

EDIT I couln't remember the link below, but finally I got it.
There's a very good article about how cmd parses batch files at
http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/4095133#4095133

SirJosh3917
Posts: 35
Joined: 02 May 2016 18:59

Re: Why won't number variables work?

#3 Post by SirJosh3917 » 30 Nov 2016 09:00

Ahh, silly me. I completely forgot about those :P
Thank you however for clearing that up :D

Post Reply