Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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% > input.txt
Model.exe < input.txt)

You could break this down in to the following steps:

  1. Assign variable 'run' a value. (e.g. 1)
  2. Concatenate this with a string ("Sim") to make a new variable, "Sim1"
  3. echo this to a text file ("input.txt")
  4. Read the variable "Sim1" from file "input.txt"
  5. Executable goes away and does its thing.
  6. 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

like image 907
Ben Williams Avatar asked Feb 24 '11 20:02

Ben Williams


1 Answers

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.)

like image 137
Gareth McCaughan Avatar answered Oct 23 '22 18:10

Gareth McCaughan