I have a batch file (in windows XP, with command extension activated) with the following line:
for /f %%s in ('type version.txt') do set VERSION=%%s
On some computer, it works just fine (as illustrated by this SO question), but on other it kills cmd (the console window just closes)
Why ?
Note: the computers seem to have a similar configuration: XpSP2, the user has administrative right, no 'Command processor" defined in HKEY_CURRENT_USER\Software\Microsoft\Command Processor...
I got a first empiric answer:
for /f %%s in (version.txt) do ...
works just fine, on every computer.
It seems for /f
works with a filename, not with any dos command like 'type filename'.
However, it is not true for all my client's computer (on some, the 'type filename' works fine)
If you want 15 (easy ?) points ;-), you can leave an answer to the question:
why 'for /f' sometime does not work with anything else than a file name. And why it just closes the DOS session ?
Edit: 3 years later(!), barlop faced a similar situation, detailed in the question "for /f
closes cmd prompt immediately?". His conclusion was:
COMSPEC
did get listed when doingSET
+ENTER.
So, I opened the environment variables window, and sawCOMSPEC
was not listed under user or system variables. I added it to System Variables, started a command prompt, and it seems to work fine.
This thread on ss64 forum, mentioned by Andriy M in his answer to barlop's question, contains the details.
The shelling out in the "
for
" loop to complete 'dir
' (or whatever command you've asked to complete) requiresComSpec
to be set in order to reload thecmd
window.
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\ComSpec=
%SystemRoot%\system32\cmd.exe
Regarding the command extensions, there is the possibility CMD.EXE is called with /E:OFF so that command extensions are disabled (even though enabled in the registry).
If using command extensions shell options in a script, it is HIGHLY suggested that you do the following trick at the beginning of your scripts.
-- Information pasted from http://www.ss64.com/nt/setlocal.html
SETLOCAL will set an ERRORLEVEL if given an argument. It will be zero if one of the two valid arguments is given and one otherwise.
You can use this in a batch file to determine if command extensions are available, using the following technique:
VERIFY errors 2>nul
SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 echo Unable to enable extensions
This works because "VERIFY errors" sets ERRORLEVEL to 1 and then the SETLOCAL will fail to reset the ERRORLEVEL value if extensions are not available (e.g. if the script is running under command.com)
If Command Extensions are permanently disabled then SETLOCAL ENABLEEXTENSIONS will not restore them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With