Question

I have a batch script that compiles and runs a Java program and as it is doing this it prints a timestamp of when the task started. I noticed that the :printDate function is being called an additional time at the very end, but :exit should end the script after "Done..." is printed.

@echo off

set PRGM=Foo
cls

call :printDate
echo Compiling...
javac %PRGM%.java

call :printDate
echo Executing...
java %PRGM%

call :printDate
echo Results...
type output.txt

call :exit

:: ----------------------------------------------------------
:: Functions
:: ----------------------------------------------------------

:printDate
for /f "tokens=2-4 delims=/ " %%a in ('echo %DATE%') do (set mydate=%%c/%%a/%%b)
for /f "tokens=1-3 delims=/:./ " %%a in ('echo %TIME%') do (set mytime=%%a:%%b:%%c)
echo|set /p=[%mydate% %mytime%] 
goto:eof

:exit
call:printDate
echo Done...
goto:eof

Here is my output

[2013/10/17 21:26:11] Compiling...
[2013/10/17 21:26:12] Executing...
[2013/10/17 21:26:12] Results...
2
6
6
5
[2013/10/17 21:26:12] Done...
[2013/10/17 21:26:12]

Edit

If anyone is interested, here is my working script: http://pastebin.com/xfwStvNK. My Java program generates the output file and the script generates the input and prints the output after compiling and running the program.

Was it helpful?

Solution

The :printDate procedure is called another time because you don't finish the execution when calling the :exit procedure, you are calling the :printDate inside the :exit procedure but after the echo Done you are returning to the call :exit line so :printDate block is processed one more time then really the goto:eof line inside the :printDate is the real end of the script.

That is the meanning of a Call, Instead you need to use the GoTo keyword, like this:

...
REM call :exit
Goto :Exit
...

...
:exit
call:printDate
echo Done...
REM goto:eof
Exit

OTHER TIPS

Always use Goto label to terminate your main program.

Example:

echo hello world<br>
call:doFirstThing<br>
call:doSecondThing<br>
<p>
Goto :FinalExit<br>
<p>
:doFirstThing<br>
echo in the first method<br>
goto:eof<br>
<p>
:doSecondThing<br>
echo in the second method<br>
goto:eof<br>
<p>
FinalExit<br>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top