Batch file: Escape questionmark in for loop
batch-file, escaping, windows
Solution
Another option is to use linefeeds within a FOR /F string. FOR /F will treat each line as an independent string. Below I show four ways to do the same thing.
@echo off
setlocal enableDelayedExpansion
:: Define LF to contain a linefeed character
set ^"LF=^
^" The above empty line is critical. DO NOT REMOVE
:: Option 1
:: Embed linefeeds directly in the string literal
for /f %%A in ("help!LF!-help!LF!--help!LF!/help!LF!?!LF!/?") do (
echo(%%A
)
echo(
:: Option 2
:: Define a variable with spaces and use search and replace
:: to substitue linefeeds
set "help=help -help --help /help ? /?"
for %%L in ("!LF!") do for /f %%A in ("!help: =%%~L!") do (
echo(%%A
)
echo(
:: Option 3
:: Embed linefeed directly in string without LF variable
for /f %%A in (^"help^
-help^
--help^
/help^
?^
/?^") do (
echo(%%A
)
echo(
:: Option 4
:: Embed linefeed directly in search and replace without LF variable
for /f %%A in (^"!help:^ ^=^
!^") do (
echo(%%A
)
I prefer option 2. I find it to be the easiest to read, yet still be compact.
Note that MC ND and I both use `echo(%%A`. This is necessary to prevent `echo /?` from displaying the help for the ECHO command.
Problem
This for loop (reduced minimal example); ``` @echo off for %%a in (help -help --help /help ? /?) do ( echo %%a ) ``` chokes on the 2 elements with a '?' character. It outputs ``` C:\Temp>test.bat help -help --help /help C:\Temp> ``` So it just quits the loop when it hits the first '?'. What is the proper escape sequence for this set? Tried a bunch of stuff, double quotes, carets, backslash, etc. but nothing seems to work.