kilves76
kilves76

Reputation: 532

cmd for loop escape ? in set?

Is there a way to escape the question mark in the for loop so that the following would work?

for %%a in (%*) do (
for %%b in (/? /h /help -h -help --help) do if %%a==%%b goto usage
)

It would be so much cleaner than separate if's. In a separate if clause %%a==/^? works but not here.

Upvotes: 2

Views: 239

Answers (2)

Jos
Jos

Reputation: 522

In addition to the "params" work-around failing when %* is empty: if you prefix %* with a space: set params= %*, it will not be empty in the %params:/?=%" and the comparison will not fail.

Upvotes: 0

Aacini
Aacini

Reputation: 67296

There is no way to preserve wild-cards * ? in a FOR (no /F) command, the only way is via a FOR /F. Note that in this case the problem exist in both FOR's, so this solution doesn't work either:

for %%a in (%*) do (
   if %%a == /? goto usage
   if %%a == /h goto usage
   . . . .
)

... unless, of course, that /? parameter is not given.

Although it is possible to assemble a loop to iterate over several switches including /?, the resulting code is more complex than individual IF's. You may try this solution instead:

setlocal EnableDelayedExpansion

set params=%*
if "%params:/?=%" neq "%params%" goto usage
for %%b in (/h /help -h -help --help) do if "!params:%%b=!" neq "%params%" goto usage

Upvotes: 3

Related Questions