Multiple do commands in a for loop: Echoing a string to a file and then redirecting to the command window
I am trying to write a batch file to iteratively execute a fortran compiled executable. Normally one would go to the windows command prompt, type 'Model.exe'. This would bring up a dos command window asking the user to type a required file name directly in to the command window at the dos prompt.
I want to write a batch file that will do this bit for me, and also iterate this step so that I can run 10 simulations consecutively instead of having to do it by hand. This kind of shell operation would be straightforward in linux, but I do not have this available.
My pseudo code would look like this:
for /L %%run in (1,1,10) do (set str=Sim%%run echo.%str%开发者_如何学Python > input.txt Model.exe < input.txt)
You could break this down in to the following steps:
- Assign variable 'run' a value. (e.g. 1)
- Concatenate this with a string ("Sim") to make a new variable, "Sim1"
- echo this to a text file ("input.txt")
- Read the variable "Sim1" from file "input.txt"
- Executable goes away and does its thing.
- Repeat steps 1 -> 5, but with a new variable calle "Sim2" etc.
I can get the above to work if I use set str=Sim1 and then echo this directly to "input.txt", but I cannot get this to work as a loop. Am I missing something?
Best regards,
Ben
Ugh, cmd.exe's treatment of variable expansion is ugly. So, you need "delayed expansion", as follows:
setlocal enabledelayedexpansion
for /L %%i in (1,1,10) do (
set str=Sim%%i
echo !str! > input.txt
Model.exe < input.txt)
endlocal
(Of course in this particular case you could just say echo Sim%%i > input.txt
but I assume there's a good reason why you want to go via another variable.)
精彩评论