As I understand the OP, the answers of Aacini and stackoverflow are wrong.
The delayed expansion solution (of Aacini) can only work if num
is defined before starting the batch, else %mnm%
will never expand.
C:\>set "num="
C:\>myBatch.bat user%num%
results to the output of
user%num%
The other solution (of stackoverflow) works a bit better, but fails when num
is defined
I added a second set num=2
to demonstrate it
@ECHO off
SET param=%1
SET num=1
CALL SET x=%param%
ECHO %x%
set num=2
CALL SET x=%param%
ECHO %x%
Calling it two times shows the problem
C:\>myBatch user%num%
user1
user2
C:\>myBatch user%num%
user2
user2
In the second run you got 2
two times, as the result is fixed at the startup of the batch.
It's a good idea to echo the content of %1
to see if the format-string is really there or if the %num%
is already expanded.
As I understand the OP (It's possible that I don't understand it!), the question is about using a placeholder,
but this is tricky with percents, as it only works at the command line (not from another batch) and it only works if the variable isn't defined in that moment.
Because, if the variable is defined, then the %num%
will expand immediatly and the content of %1
is user2
and not user%num%
(assuming num=2).
That it sometimes works is only a side effect of the cmd-line parser, as it does not remove an undefined variable (as inside a batch file), instead an undefined variable expansion will not changed in any way.
echo "%thisIsUndefined%" - from cmd-line this outputs `"%thisIsUndefined%"`
echo "%thisIsUndefined%" - from a batch file this outputs `""`
But as side effect, there doesn't exists a way to escape a percent sign in cmd-line context.
There exists only a workaround for a pseudo escape.
mybatch user%num^%
It doesn't really escapes the percent, but mostly there will not exists a variable named num^
.
Then the solution of stackoverlow would work, with:
myBatch user%num^%
But I would prefere the delayed expansion, mentioned by Aacini.
You would call the batch then with exclamation marks, instead of percents, normally this works good, as delayed expansion is per default disabled.
myBatch user!num!
The batch itself would look like this
@echo off
set "param=%1"
Setlocal EnableDelayedExpansion
set num=1
echo %param%
set num=2
echo %param%