Page 1 of 1

Why won't number variables work?

Posted: 29 Nov 2016 23:41
by SirJosh3917
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.

Re: Why won't number variables work?

Posted: 30 Nov 2016 04:24
by elzooilogico
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

Re: Why won't number variables work?

Posted: 30 Nov 2016 09:00
by SirJosh3917
Ahh, silly me. I completely forgot about those :P
Thank you however for clearing that up :D