Jared Allard
Jared Allard

Reputation: 933

Escaping characters in a for loop in batch

Alright, so let's say we have a file called start.cmd

@echo off

set value=1
for /D %%a in (%*) do (
    echo %%a
)

start.cmd is called by

start.cmd ^%value^% ^%anothervalue^%

The for loop would, of course, take %1, and %2, and so forth.

My question is:

EDIT: How can I escape a value within another value?

Upvotes: 2

Views: 615

Answers (1)

jeb
jeb

Reputation: 82420

I make a guess:

You want to expand the variables just in the for loop, not before.

With your case you only need to add a CALL, as it starts the parser a second time, so it can expand the %value% before it echo it.

@echo off

set value=1
for /D %%a in (%*) do (
    call echo %%a
)

But better is to use delayed expansion here

@echo off
setlocal EnableDelayedExpansion
set value=1
for /D %%a in (%*) do (
    echo %%a
)

Then you can start your batch with

start.cmd !value! !anothervalue!

This works as delayed expansion is done after the percent expansion by the parser, so %* is expanded to !value! !anothervalue! and then it's expanded to 1 xyz

Upvotes: 1

Related Questions