问题
I am getting a weird error in my batch program. I think the problem is in enable delayed expansion, but the fix I apply doesn't work. This is my code:
setlocal ENABLEDELAYEDEXPANSION
for /l %%x in (1, 1, 3) do (
set ff=Firefox_45_0.0_%%x
echo %%x
firefox.exe -CreateProfile "%ff% %homedrive%%homepath%\Desktop\Firefoxes\Profiles\Firefox_45_0.0_%%x"
)
ff doesn't have any value, although I used delayed expansion. What could be the fix?
EDIT: command printed to console (I don't use @echo off)
C:\Users\Home2\Desktop\Firefoxes\Versions\Firefox_45_0.0>(
set ff=Firefox_45_0.0_1
echo 1
firefox.exe -CreateProfile "!ff! C:\Users\Home2\Desktop\Firefoxes\Profiles\Firefox_45_0.0_1"
)
What is funny is that it actually performs as expected, although it prints !ff! in the console.
回答1:
!ff!
fixes it, as delayed expansion uses exclamation marks instead of percent signs.
Delayed expansion mode doesn't change the percent expansion, it adds a new and better way for expansion.
Delayed expansion is disabled by default.
To enable it in a batch file use
setlocal EnableDelayedExpansion
set "var=Hello world"
echo !var!
Attention:
On the command line the command setlocal EnableDelayedExpansion
has no effect at all.
You could enable it by starting a new cmd.exe instance with cmd /v:on
回答2:
The delayed expansion did not work on Win 10 I tested, from command line.
SETLOCAL EnableDelayedExpansion
SETLOCAL EnableExtensions
The code below worked (to answer the question), without delayed expansion:
for /l %x in (1, 1, 3) do (
rem set ff=Firefox_45_0.0_%x
echo Firefox_45_0.0_%x
firefox.exe -CreateProfile "Firefox_45_0.0_%x %homedrive%%homepath%\Desktop\Firefoxes\Profiles\Firefox_45_0.0_%x"
)
Win 10 CMD doesn't allow changes to SETLOCAL on command line. OK for batch files:
Delayed environment variable expansion is NOT enabled by default. You can enable or disable delayed environment variable expansion for a particular invocation of CMD.EXE with the /V:ON or /V:OFF switch. You can enable or disable delayed expansion for all invocations of CMD.EXE on a machine and/or user logon session by setting either or both of the following REG_DWORD values in the registry using REGEDIT.EXE:
HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\DelayedExpansion
and/or
HKEY_CURRENT_USER\Software\Microsoft\Command Processor\DelayedExpansion
to either 0x1 or 0x0. The user specific setting takes precedence over the machine setting. The command line switches take precedence over the registry settings.
In a batch file the SETLOCAL ENABLEDELAYEDEXPANSION or DISABLEDELAYEDEXPANSION arguments takes precedence over the /V:ON or /V:OFF switch. See SETLOCAL /? for details.
If delayed environment variable expansion is enabled, then the exclamation character can be used to substitute the value of an environment variable at execution time.
来源:https://stackoverflow.com/questions/38805476/enable-delayed-expansion-doesnt-work