Batch Functions: goto:eof, exit /b and structure.

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Message
Author
shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Batch Functions: goto:eof, exit /b and structure.

#1 Post by shadeclan » 02 Jun 2011 12:03

On a hunch, I created and successfully executed a batch script while ending the function with "exit /b" instead of "goto:eof". The "/b" assures that only the function is exited (according to the MS help file) and not the entire script. I thought the "exit /b" at the end made the code easier to understand and a little closer to the structure of other programming languages.

I also thought it would be better programming practice and improve the structure of the batch script to put function declarations at the top of the script together with variable declarations. In my own code, I'm standardizing on the labels "BEGIN" and "END" to de-mark the program execution area.

I greatly appreciated the FTP and Function tutorial portions of the DOS Tips website - it was a great help to me, since I needed an FTP script. I modified the DOS Tips code according to the structure I'm suggesting. I also added a little error handling - I write to the log file on a failure to download a given file but there are other things that could be done, such as sending an email or raising a popup on failure:

Code: Select all

@echo off
setlocal

rem -------------------------------------------------------------------
rem -----------------Global Variable declarations----------------------
rem -------------------------------------------------------------------
rem Date/time variables for file naming and date formatting
rem year, month, day, weekday, hour, minute, second
set vYr=%date:~10,4%
set vMon=%date:~4,2%
set vDay=%date:~7,2%
set vWkDay=%date:~0,3%
set vHr=%time:~0,2%
set vMn=%time:~3,2%
set vSec=%time:~6,2%

rem ---The following variables are for ease in maintaining &        ---
rem ---changing common parameters in the batch job.                 ---
rem Set app name - used for logfile name.
set vAppName=WhateverApp

rem Set logfile name.
rem vLogfile variable can be configured to overwrite the log file each
rem time the job runs.  It can also be configured to write a series of
rem logs and overwrite them every week, month, year or never. 
rem Overwrite logfile each run
set "vLogFile=%vAppName%Log.txt"
rem Weekly series.  Overwrite log files each week.
rem set vLogFile="%vAppName%Log %vWkDay%.txt"
rem Monthly series.  Overwrite log files each month.
rem set vLogFile="%vAppName%Log %vDay%.txt"
rem Ininfite Series.  Never overwrite log.
rem set vLogFile="%vAppName%Log %vYr%%vMon%%vDay%%vHr%%vSec%.txt"

rem FTP server name.
set "vFTPSvr=SomeFTPServer"
rem FTP server user name.
set "vFTPUser=SomeUsername"
rem FTP user password.
set "vFTPPass=SomePassword"
rem FTP directory where download file can be found.
set "vFTPDir=/some/FTP/directory"
rem Local directory where file will be placed.
set "vLocalDir=C:\Some\Destination\Computer\Folder"

rem Returning variable indicating if a function worked.
set "vResult=0"

rem -------------------------------------------------------------------
rem --------------------Function declarations--------------------------
rem -------------------------------------------------------------------
goto:BEGIN
:GetFile
rem This function creates the required feeder file for the FTP
rem app.  Dependencies are vLogFile, vFTPSvr, vFTPUser, vFTPPass,
rem vFTPDir and vLocalDir.
rem Parameters are:
rem   Param1 = Name of target file on FTP server
rem   Param2 = Name of file after it has been downloaded.
rem   Param3 = What to change the name of the file on the FTP server.
setlocal
   rem load parameters into variables
   rem Target FTP file name
   set "vFTPFile=%~1%"
   rem Name of FTP'd file on server
   set "vLocalFile=%~2%"
   rem New name of file on FTP server.
   set "vRenameFile=%~3%"
   rem ---Write commands to FTP Command file.---
   rem Replace FTP Command file contents.
   rem Connect to FTP server.
   @echo open %vFTPSvr% > "%vAppName% FTP.txt"   
   @echo user %vFTPUser% %vFTPPass% >> "%vAppName% FTP.txt"
   rem Change directories to desired locations.
   @echo lcd "%vLocalDir%" >> "%vAppName% FTP.txt"
   @echo cd "%vFTPDir%" >> "%vAppName% FTP.txt"
   
   rem if the name of the target file is to be the same on both the
   rem FTP server and the local server, construct the GET statement
   rem to default to the same name in both places.
   if "%vFTPFile%"=="%vLocalFile%" (
      @echo get "%vFTPFile%" >> "%vAppName% FTP.txt"
   )else (
      @echo get "%vFTPFile%" "%vLocalFile%" >> "%vAppName% FTP.txt"
   )
   
   rem Do not add the rename portion of the code if the file on the
   rem FTP server if the renaming is the same as the current name.
   if not "%vRenameFile%"=="%vFTPFile%" (
      @echo delete "%vRenameFile%" >> "%vAppName% FTP.txt"
      @echo rename "%vFTPFile%" "%vRenameFile%" >> "%vAppName% FTP.txt"
   )
   
   rem Add code to close the FTP server connection and terminate the
   rem FTP app.
   @echo disconnect >> "%vAppName% FTP.txt"
   @echo bye >> "%vAppName% FTP.txt"

rem   goto:SkipFTP&rem Comment in for debugging.
   rem Execute FTP step.
   call ftp -i -n -s:"%vAppName% FTP.txt" >> %vLogFile%

:SkipFTP
   
rem   goto:SkpDeCmd&rem Comment in for debugging.
   rem Cleanup - delete FTP Command file.
   if exist "%vAppName% FTP.txt" del /q "%vAppName% FTP.txt"
:SkpDeCmd

(endlocal
   rem Return the number of times in the logfile that files were
   rem successfully transferred from the FTP server.
   set "%~4=0"
   if exist "%vLogFile%" (
      for /f "tokens=1,2,* skip=1" %%a in ('find /c "226 Transfer complete." %vLogFile%') do (
         set "%~4=%%c"
      )
   )
)
exit /b 0

rem -------------------------------------------------------------------
rem --------------------Begin Program Execution------------------------
rem -------------------------------------------------------------------
:BEGIN
rem Switch to desired working directory
cd /d "C:\Directory\Where\I_Keep\Batch_Routines"

rem Overwrite existing or create new logfile with new load time
rem and load results.
@echo ---- Executed %date% %time% ---- > %vLogFile%

rem Retrieve files from FTP server.
call:GetFile "Some_FTP.txt", "Some FTP.txt", "Some_FTP.BU", vResult
if %vResult%==1 (
   @echo ***Successfully downloaded Some_FTP.txt*** >> %vLogFile%
)else (   
   @echo ***Unable to download Some_FTP.txt*** >> %vLogFile%
   goto:END
)
   @echo. >> %vLogFile%&@echo. >> %vLogFile%
   
call:GetFile "SomeOther_FTP.txt", "Some Other FTP.txt", "SomeOther_FTP.bu", vResult
if %vResult%==2 (
   @echo ***Successfully downloaded SomeOther_FTP.txt*** >> %vLogFile%
)else (   
   @echo ***Unable to download SomeOther_FTP.txt*** >> %vLogFile%
   goto:END
)
   @echo. >> %vLogFile%&@echo. >> %vLogFile%

:END
pause
endlocal
exit /b 0
exit


The double exit at the end assures that, if the program is called from another batch script, it terminates properly and returns control to the calling batch script.

Hope this helps someone.
Last edited by shadeclan on 02 Jun 2011 12:46, edited 1 time in total.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#2 Post by Ed Dyreen » 02 Jun 2011 12:34

exit /b 0
exit

When would it not terminate properly ?

Only one exit is enough to end the batch, an exit command does not fail.
Furthermore, your last exit command will not return to the calling batch, It will terminate both !

But an exit /b is indeed better than a goto :eof
It allows us to use return-codes and is noticably faster when used in larger scripts.

Please explain, why we need multiple exit commands.

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#3 Post by shadeclan » 02 Jun 2011 13:05

When would it not terminate properly ?

I have a batch routine that I run every morning to start applications I use every day and configure my desktop environment to my liking. I run a batch job instead of shoving shortcuts in the startup folder so that I can control when the applications start up - it actually takes longer and causes system conflicts if I try to start them all together. My startup batch job calls several secondary batch jobs which actually start the applications (these batch files will simply make the application active if it is already running and do some backup functions as well - I also have my application shortcuts pointing to them for the same reasons). When I was writing the files, I was having problems with the secondary batch files not terminating properly. I stumbled on the double exit method and I haven't had the problem since.

Furthermore, your last exit command will not return to the calling batch, It will terminate both !

I understand your concern, but it really is no problem. If the first exit, "exit /b" is successful, the second exit is never executed as control is returned to the calling batch job before reaching the second "exit". If the first "exit" is not successful, than the second "exit" is executed on the same batch file, assuring control is returned to the calling batch job.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#4 Post by Ed Dyreen » 02 Jun 2011 15:07

I do believe you may have had problems, but I also believe your coding has something to do with it.
You may use a batch to start some batches that do stuff.

I have batches, &programs that format &install a complete OS from the botom up, configure it &install 3thparty software using various languages, mostly batch.
They took me years to devellop, totalling about 1.000.000 chars.
Batches that start over 30 other batches simultaniously, running parrallel, monitor their progress &preparing the next move are no exception.

I'm not trying to look cool, I'm just a nerd trying to explain you really don't need to exit more than once. :o

goto, call &exit are closely related; a batch that uses call 100 times also needs exit or goto :eof 100 times.
If this works for you, then that's great but,
it would be a bad idea if we all started doing this.

Don't feel attacked, I see you're new so just to make sure: we are all friends here :D

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#5 Post by shadeclan » 03 Jun 2011 06:51

Ed Dyreen wrote:I do believe you may have had problems, but I also believe your coding has something to do with it.
That's always possible. I don't claim to be the world's greatest programmer but I do enjoy it. I'm one of those weirdos that write code in their spare time even though I code for a living.
I was using "START /b /wait" to start the secondary batch jobs before I realized that "CALL" would also wait for the secondary batch jobs to terminate before continuing so that was probably it.

Ed Dyreen wrote:I have batches & programs that format & install a complete OS from the bottom up, configure it & install 3rd party software using various languages, mostly batch.
They took me years to develop, totaling about 1.000.000 chars.
Batches that start over 30 other batches simultaneously, running parallel, monitor their progress & preparing the next move are no exception.

I'm not trying to look cool, I'm just a nerd trying to explain you really don't need to exit more than once. :o
Well, from one nerd to another, I'm glad that one of us here knows what they're doing! :D

Ed Dyreen wrote:goto, call & exit are closely related; a batch that uses call 100 times also needs exit or goto:eof 100 times.
If this works for you, then that's great but it would be a bad idea if we all started doing this.
Again, I understand your concern. The second "EXIT" does give me some peace of mind: it adds only a few extra bytes overall to the code, it is only useful at the very end of a batch script, not for internally defined functions and it is only executed if necessary so I'll continue using it. If someone else is having the same problems I was having, the technique might come in handy for them. It's a non-standard world out there, full of strange configurations - I have problems with some of my applications that can't be duplicated: for example, one app freezes up when I access the help file - I have to access the help file outside the program. The problem will probably only be solved by reformatting the hard drive and reloading the OS - oh, the joy of Microsquish.

Ed Dyreen wrote:Don't feel attacked, I see you're new so just to make sure: we are all friends here :D
Well, as with most programmers, your bedside manner could use a little work but thank you for your comments. I will certainly know where to go if I run into a coding problem and I appreciate people who are willing to share their knowledge as I also try to take the time to share what I learn with others.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#6 Post by Ed Dyreen » 03 Jun 2011 07:14

your bedside manner

Don't understand that sorry, I forgot to tell English is not my native language. You may or may not already have noticed. Could you repeat that with different words? Apart from this sentence I understood everything you wrote.

I've tried:
START /b /wait CMD
exit
I don't see any problems here &it works for me, so can't help u on that.

But I also know CMD can sometimes cause other applications that have been started with it to behave strange or not at all when a large amount of variables are loaded.

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#7 Post by shadeclan » 03 Jun 2011 07:44

Ed Dyreen wrote:
your bedside manner

Don't understand that sorry, I forgot to tell English is not my native language. You may or may not already have noticed. Could you repeat that with different words? Apart from this sentence I understood everything you wrote.

Oh, sorry. I always assume that English is the first language unless it is extremely obvious. I want to be careful not to inadvertently insult someone - the written word (even more so than speech) doesn't always carry the precise meaning or emotional intent of the speaker.

Your English is actually quite good - just a few slight word order and phrasing differences which do not affect the meaning of what you're trying to convey. Besides, I'm an American. So many people from so many different places have settled here that the name "Dyreen" does not sound foreign to me. It's Dutch, yes?

"Bedside manner" refers to the way a doctor treats a patient. A poor "bedside manner" means that the doctor treats his sick patients in a somewhat less than kind and empathetic manner. Most real programmers of my acquaintance don't possess great people skills and tend to approach social interactions more directly and abruptly than others. I think it just comes with the territory - most programmers prefer working with computers than with people. I can frequently relate to situations in the Dilbert comic strip - I read it every day.

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#8 Post by shadeclan » 03 Jun 2011 07:59

Ed Dyreen wrote:I've tried:
START /b /wait CMD
exit
I don't see any problems here &it works for me, so can't help u on that.

But I also know CMD can sometimes cause other applications that have been started with it to behave strange or not at all when a large amount of variables are loaded.
Try using "START /b /wait" to start a batch job which also has "START" in it to start an application. You might be able to duplicate the problem then. Basically, what happens is that the program just hangs without the second exit.

I am using CMDOW to loop through the windows of a program to dig out the right one to restore / activate / close the application. Some of the variables in the loop require the batch job to run under "setlocal enabledelayedexpansion" - this may have some effect on how the subprogram terminates. I've used COBOL 76 before and know the limitations on nested IF statements inherent in that language so I just figure that this and your large variable number problem is some sort of problem like that.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#9 Post by Ed Dyreen » 04 Jun 2011 01:20

I'm an American. So many people from so many different places have settled here that the name "Dyreen" does not sound foreign to me. It's Dutch, yes?

Incredible!, I made the name up to use it as my nickname. I did not know it actually exists! Talking about coincidence :shock:
And no it isn't Dutch, dutch names are like Tim, Ben, David, Kim, Ellen, Gerard, Piet, Kevin,...
America has deep relations with GB,The Netherlands &Belgium.. Because of it's history..
New York was actually owned once by Dutch people, they called it New Amsterdam.

I've created 2 batches:
TST0.CMD

Code: Select all

@echo off
title CMD_0
pause
start "CMD_1" /b /wait CMD /c "tst1.CMD"
title CMD_0
pause
exit /b

TST1.CMD

Code: Select all

@echo off
title CMD_1
pause
start "CMD_2" /b /wait CMD /c "title CMD_2 &pause"
title CMD_1
pause
exit /b

It doesn't hangs so... but it has never been a problem with me &you solved it using the call command. So we both don't have any problem. 8)

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#10 Post by shadeclan » 06 Jun 2011 06:36

Ed Dyreen wrote:Incredible!, I made the name up to use it as my nickname. I did not know it actually exists! Talking about coincidence :shock:
Oh, this is hilarious! I was about to ask you where you were and only now noticed that the left column where the user names shows your location as "Flanders"! Just call me Mr. Observant! :roll:

Actually, I did know that NY used to be New Amsterdam and, in fact, the Dutch had a much better relationship with the native inhabitants than the English ever did (or, for that matter, better than our current government). My interests, along with programming, lie in history and economics. The Dutch have a proud history of economic freedom although, comically enough, I don't know what your current national economics are right now. :oops:

Ed Dyreen wrote:I've created 2 batches:
...
It doesn't hangs so... but it has never been a problem with me & you solved it using the call command. So we both don't have any problem. 8)
Yup - no sense beating a dead horse.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#11 Post by Ed Dyreen » 06 Jun 2011 07:40

shows your location as "Flanders"! Just call me Mr. Observant!

I've just recently exposed my origin, you couldn't have known it before :wink:

The impact of the financial crisis was hardly felt by the 'working-class'. It was mainly in America I guess. And yes econimics are pretty stable, don't know about the future though. Because countries are lending each other huge amounts of money. And if one goes down, we'll all go down. :(

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#12 Post by shadeclan » 06 Jun 2011 10:14

Ed Dyreen wrote:I've just recently exposed my origin, you couldn't have known it before :wink:
Oh, good. I'm not a complete moron then! :D

Ed Dyreen wrote:And if one goes down, we'll all go down. :(
Belgium is in the EU then? Bad move. Things don't look so good, with Portugal, Italy, Greece and Spain being bailed out by the trillions. Of course, that doesn't keep the EU on a par with US expenditures - not only do we throw trillions of dollars away on bailouts to corporations that cozy up to government fat cats but we are also throwing away additional trillions in useless, un-winnable wars against ideas like "terrorism" and "drug use", not to mention the money we spend on maintaining military bases all over the world, so I won't.

But I digress. This is supposed to be a DOS Batch forum - not a socio-economic political forum. Sorry.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#13 Post by Ed Dyreen » 06 Jun 2011 10:24

We already solved no problem. And it's your thread, you talk about whatever you want. Or is this no problem of us showed up again. Just post a bit of code here und there, then people'll think we have a problem :mrgreen:

shadeclan
Posts: 61
Joined: 02 Jun 2011 11:29
Location: USA - Somewhere between Albany NY and Bennington VT

Re: Batch Functions: goto:eof, exit /b and structure.

#14 Post by shadeclan » 06 Jun 2011 10:38

Ed Dyreen wrote:We already solved no problem. And it's your thread, you talk about whatever you want. Or is this no problem of us showed up again. Just post a bit of code here and there, then people'll think we have a problem :mrgreen:

LOL!

On most forums, sticking to the topic is strictly enforced. It might be that this particular forum isn't visited all that often - I'm sure most people are migrating to Win7 :P and PowerShell. Still, for those of us still using XP and earlier versions of Windows, this forum has a great deal of useful information. I'm seriously considering compiling the website into a PDF for reference - you can never be sure if a given site will be available in another day, month or year.

Ed Dyreen
Expert
Posts: 1569
Joined: 16 May 2011 08:21
Location: Flanders(Belgium)
Contact:

Re: Batch Functions: goto:eof, exit /b and structure.

#15 Post by Ed Dyreen » 06 Jun 2011 10:47

Trust me, as a programmer you are always behind. I learned that very quickly. It's impossible to wan't everything & keep up if you have to maintain X amount of software. I have a functional i386 33Mhz 4MB made in Germany 1982, running DOS 6.22 &win95. Am I behind, probably :lol:
On most forums, sticking to the topic is strictly enforced.

This forum is no different, so don't open 10 threads talking about airplanes, but I've seen some others well off-topic too. :roll:

Post Reply