Search code examples
windowsfunctionbatch-filejavacgoto

Windows batch function gets called an extra time


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.


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