I'm trying to understand where in the code exactly does GOTO :EOF return to?
Here is the code:
SET count=1
FOR /f "tokens=*" %%G IN (somefile.txt) DO (call :subroutine "%%G")
GOTO :EOF
:subroutine
echo %count%:%1
set /a count+=1
GOTO :EOF
:EOF is a predefined label as Microsoft explains in documentation for command GOTO. The help output by running in a command prompt window goto /? explains also this special label for End Of File. But this predefined label is supported only with command extensions being enabled as by default.
The help output by running in a command prompt window call /? and of course also the documentation for command CALL explain both that goto :EOF should be used to exit a subroutine called with call :Label.
A subroutine is nothing else than another batch file embedded within current batch file called with command call. If the subroutine is at end of the batch file, real end of file marks the end of the subroutine.
But there can be multiple subroutines in a batch file.
So a command is needed for command interpreter to exit the subroutine on reaching a specific line in command processing and go back to the calling command line. goto :EOF as well as exit /B can be both used everywhere to either exit a subroutine or exit the current batch file processing.
In batch code in question the first goto :EOF is needed to exit batch file processing without an unwanted fall through to the subroutine code after finishing the loop.
The second goto :EOF in batch code of questioner is for exiting the subroutine and continue processing in FOR loop in second line. It does not exit processing of the batch file, it exits only the processing of the subroutine.
Note 1: goto EOF without a colon requires that there is really a line starting with :EOF in the batch file, i.e. the label EOF must exist in the file. goto :EOF always results in exiting subroutine/batch processing with command extensions enabled even if there is a label EOF in the batch file because of a line starting with :EOF.
Note 2: Command EXIT without parameter /B results always in exiting entire command process independent on calling hierarchy and independent on how the Windows command processor was started – with parameter /K to keep cmd.exe running as used when opening a command prompt window or with /C to close after command processing finished as used on double clicking a batch file. Therefore exit without /B should be used wisely in a batch file (best: never).
Note 3: exit /B without or with an exit code works always, but outputs an error message with command extensions disabled as demonstrated by this code:
#echo off
setlocal DisableExtensions
echo Use command exit /B with command extensions disabled.
exit /B 5
echo This line is not processed anymore.
Executing this batch file from within a command prompt window results in output of the error message:
The system cannot find the batch label specified - EOF
But the processing of the batch file is exited nevertheless with the exit code value 5 as it can be seen on running next in same command prompt window echo ERRORLEVEL is: %ERRORLEVEL% which outputs: ERRORLEVEL is: 5
It looks like there is assigned first the specified exit code value 5 to the dynamic variable ERRORLEVEL on using exit /B 5 and next is executed goto :EOF because of option /B. That fails because of disabled command extensions resulting in the error message and in exiting the batch file processing as it always occurs on a label to go to does not exist in a batch file.
In other words exit /B without or with an additional exit code always works, but there should be appended 2>nul to suppress the error message on command extensions disabled, i.e. use exit /B 2>nul (without exit code) or exit /B 5 2>nul (with exit code)
Note 4: ERRORLEVEL is not affected by goto :EOF, but the Microsoft GOTO documentation is mute on this topic. exit /B # sets ERRORLEVEL to # as documented by Microsoft. exit /B # can be also used instead of goto :EOF to exit a subroutine with a specific exit code evaluated on the command line calling the subroutine like on using the operators && or || or on next command after calling command line with if errorlevel X. However, explicitly exiting a batch file or a subroutine with a specific exit code is usually not needed as neither goto :EOF nor exit /B modify the current value of ERRORLEVEL.
Note 5: Do not use goto:EOF or call:Label in a batch file with no space between command GOTO respectively CALL (argument 0) and the label (argument 1). There should be always used goto :EOF and call :Label with a space as argument strings separator between command and label. The reason is that goto:EOF results in the attempts to find in current directory first a file with name goto: and next a file with name goto:EOF. The incorrect command call:Label results in searching for a file with name call: and next with name call:Label. The file system returns for both syntactically wrong commands twice to cmd.exe that the name is invalid. Then cmd.exe detects the colon as reason for the invalid name and splits the command up into command and label argument and finally runs the command with success. The usage of goto :EOF and call :Label does not cause any wrong file system accesses as cmd.exe immediately recognizes the string goto respectively call as internal command.
For details on ERRORLEVEL behavior see:
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
Single line with multiple commands using Windows batch file
GOTO :EOF is functionally equivalent to exit /B, but both forms only works when Extensions are enabled. The test for this point is very simple:
setlocal DisableExtensions
goto :EOF
Compare previous code vs. this one:
setlocal DisableExtensions
exit /B
This means that GOTO :EOF returns to the same point where exit /B would return.
:eof means "End of file". It's used to make the script finish without executing any of the commands below.
As the GOTO and CALL are using the same functionality to find a label you have an option to access the :EOF with CALL too:
CALL ::EOF
Same as GOTO (when CALL with the additional semicolon) the actual end-of-file will be the preferable point where the flow of the script will go. If you have your own label\function defined with EOF you can access it with single semicolon.
Though calling the :EOF has no much use - you can't put a code after the end of file so this line is actually doing nothing (though this will hit the performance as the end of file is parsed). And as GOTO and EXIT /B this wont work without enabled extensions.
Related
I'm trying to understand where in the code exactly does GOTO :EOF return to?
Here is the code:
SET count=1
FOR /f "tokens=*" %%G IN (somefile.txt) DO (call :subroutine "%%G")
GOTO :EOF
:subroutine
echo %count%:%1
set /a count+=1
GOTO :EOF
:EOF is a predefined label as Microsoft explains in documentation for command GOTO. The help output by running in a command prompt window goto /? explains also this special label for End Of File. But this predefined label is supported only with command extensions being enabled as by default.
The help output by running in a command prompt window call /? and of course also the documentation for command CALL explain both that goto :EOF should be used to exit a subroutine called with call :Label.
A subroutine is nothing else than another batch file embedded within current batch file called with command call. If the subroutine is at end of the batch file, real end of file marks the end of the subroutine.
But there can be multiple subroutines in a batch file.
So a command is needed for command interpreter to exit the subroutine on reaching a specific line in command processing and go back to the calling command line. goto :EOF as well as exit /B can be both used everywhere to either exit a subroutine or exit the current batch file processing.
In batch code in question the first goto :EOF is needed to exit batch file processing without an unwanted fall through to the subroutine code after finishing the loop.
The second goto :EOF in batch code of questioner is for exiting the subroutine and continue processing in FOR loop in second line. It does not exit processing of the batch file, it exits only the processing of the subroutine.
Note 1: goto EOF without a colon requires that there is really a line starting with :EOF in the batch file, i.e. the label EOF must exist in the file. goto :EOF always results in exiting subroutine/batch processing with command extensions enabled even if there is a label EOF in the batch file because of a line starting with :EOF.
Note 2: Command EXIT without parameter /B results always in exiting entire command process independent on calling hierarchy and independent on how the Windows command processor was started – with parameter /K to keep cmd.exe running as used when opening a command prompt window or with /C to close after command processing finished as used on double clicking a batch file. Therefore exit without /B should be used wisely in a batch file (best: never).
Note 3: exit /B without or with an exit code works always, but outputs an error message with command extensions disabled as demonstrated by this code:
#echo off
setlocal DisableExtensions
echo Use command exit /B with command extensions disabled.
exit /B 5
echo This line is not processed anymore.
Executing this batch file from within a command prompt window results in output of the error message:
The system cannot find the batch label specified - EOF
But the processing of the batch file is exited nevertheless with the exit code value 5 as it can be seen on running next in same command prompt window echo ERRORLEVEL is: %ERRORLEVEL% which outputs: ERRORLEVEL is: 5
It looks like there is assigned first the specified exit code value 5 to the dynamic variable ERRORLEVEL on using exit /B 5 and next is executed goto :EOF because of option /B. That fails because of disabled command extensions resulting in the error message and in exiting the batch file processing as it always occurs on a label to go to does not exist in a batch file.
In other words exit /B without or with an additional exit code always works, but there should be appended 2>nul to suppress the error message on command extensions disabled, i.e. use exit /B 2>nul (without exit code) or exit /B 5 2>nul (with exit code)
Note 4: ERRORLEVEL is not affected by goto :EOF, but the Microsoft GOTO documentation is mute on this topic. exit /B # sets ERRORLEVEL to # as documented by Microsoft. exit /B # can be also used instead of goto :EOF to exit a subroutine with a specific exit code evaluated on the command line calling the subroutine like on using the operators && or || or on next command after calling command line with if errorlevel X. However, explicitly exiting a batch file or a subroutine with a specific exit code is usually not needed as neither goto :EOF nor exit /B modify the current value of ERRORLEVEL.
Note 5: Do not use goto:EOF or call:Label in a batch file with no space between command GOTO respectively CALL (argument 0) and the label (argument 1). There should be always used goto :EOF and call :Label with a space as argument strings separator between command and label. The reason is that goto:EOF results in the attempts to find in current directory first a file with name goto: and next a file with name goto:EOF. The incorrect command call:Label results in searching for a file with name call: and next with name call:Label. The file system returns for both syntactically wrong commands twice to cmd.exe that the name is invalid. Then cmd.exe detects the colon as reason for the invalid name and splits the command up into command and label argument and finally runs the command with success. The usage of goto :EOF and call :Label does not cause any wrong file system accesses as cmd.exe immediately recognizes the string goto respectively call as internal command.
For details on ERRORLEVEL behavior see:
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
Single line with multiple commands using Windows batch file
GOTO :EOF is functionally equivalent to exit /B, but both forms only works when Extensions are enabled. The test for this point is very simple:
setlocal DisableExtensions
goto :EOF
Compare previous code vs. this one:
setlocal DisableExtensions
exit /B
This means that GOTO :EOF returns to the same point where exit /B would return.
:eof means "End of file". It's used to make the script finish without executing any of the commands below.
As the GOTO and CALL are using the same functionality to find a label you have an option to access the :EOF with CALL too:
CALL ::EOF
Same as GOTO (when CALL with the additional semicolon) the actual end-of-file will be the preferable point where the flow of the script will go. If you have your own label\function defined with EOF you can access it with single semicolon.
Though calling the :EOF has no much use - you can't put a code after the end of file so this line is actually doing nothing (though this will hit the performance as the end of file is parsed). And as GOTO and EXIT /B this wont work without enabled extensions.
If a script which should get exited in subroutines without closing the terminal when calling EXIT 1. There for I use this if which calls the script again.
This worked fine until I now discovered some issue with a quoted vertical bar as a parameter "!". I get an error stating that the command is misspelled.
Here is the part of the script that fails:
#ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
IF "%selfWrapped%"=="" (
REM this is necessary so that we can use "exit" to terminate the batch file,
REM and all subroutines, but not the original cmd.exe
SET selfWrapped=true
%ComSpec% /s /c ""%~0" %*"
GOTO :EOF
)
echo %*
ENDLOCAL
EXIT /B 0
Call:
test.cmd "hello world" "|"
Expected Output:
"hello world" "|"
I checked the the value of %* inside the IF but for it seems totally legitimate to use a vertical bar as well as any other quoted string.
So...
Why does the script fails?
How can I fix it?
I do not agree with some of the description in the link.
See exit /? accurate help description.
exit exits the interpreter.
exit 1 exits the interpreter with exitcode 1.
exit /b has similar behavior as goto :eof which exits
the script or called label. Errorlevel is not reset so allows
errorlevel from the previous command to be accessable after
exit of the script or the called label.
exit /b 1 exits the script or the called label with errorlevel 1.
If you oddly use exit /b at a CMD prompt, it is going to exit the interpreter.
Main code:
#ECHO OFF
SETLOCAL DISABLEDELAYEDEXPANSION
SET args=%*
SET "self=%~f0"
IF "%selfWrapped%"=="" (
#REM this is necessary so that we can use "exit" to terminate the batch file,
#REM and all subroutines, but not the original cmd.exe
SET "selfWrapped=true"
SETLOCAL ENABLEDELAYEDEXPANSION
ECHO !ComSpec! /s /c ""!self!" !args!"
"!ComSpec!" /s /c ""!self!" !args!"
GOTO :EOF
)
ECHO(%*
EXIT /B 0
Both use of GOTO :EOF and EXIT /B 0 will exit the script.
ENDLOCAL is implied at exit of the script.
Explicit use of ENDLOCAL is for when you want to end the
current local scope and continue the script. As always, being
explicit all the time is a choice.
Setting %* to args keeps the double quoting paired.
Quoting i.e. set "args=%*" can cause issue sometimes
though not using quotes allow code injection i.e.
arguments "arg1" ^& del *.*. If the del *.* is not going
to execute at the set line, then it will probably happen
at the ComSpec line. For this example, I chose not quote.
So, it is a choice.
You are using disabled expansion at start of the script. That
saves the ! arguments which is good. Before you execute
ComSpec though, enable delayed expansion and use !args!
which is now protected from the interpreter now not seeing |
or any other special character which may throw an error.
Your script fails as the | argument is exposed.
C:\Windows\system32\cmd.exe /s /c ""test.cmd" " | ""
The above is echoed evaluation of the ComSpec line with
setting #ECHO ON. Notice the pairing of quotes
i.e. "", " " and "". Notice the extra spacing inserted
around the | character as the interpreter does not consider
it as part of a quoted string.
Compared to updated code changes of echoed evaluation...:
"!ComSpec!" /s /c ""!self!" !args!"
The string between the quotes remain intact. No extra spacing
inserted into the string. The echoed evalution looks good and
executes good.
Disclaimer:
Expressing the workings of CMD is like walking a tight rope.
Just when you think you know, fall off the rope you go.
I don't see the necessity to append the parameter to your %ComSpec% /s /c ""%~0" %*" at all.
As you already use a variable (selfWrapped) to detect, if the wrapper call is necessary, you could also put your arguments into a variable.
set args=%*
Then you can simply use !args! in your child instance.
#ECHO OFF
setlocal DisableDelayedExpansion
IF "%selfWrapped%"=="" (
#REM this is necessary so that we can use "exit" to terminate the batch file,
#REM and all subroutines, but not the original cmd.exe
SET "selfWrapped=true"
SET ^"args=%*"
"%ComSpec%" /s /c ""%~f0""
GOTO :EOF
)
:Main
setlocal EnableDelayedExpansion
ECHO(!args!
EXIT /B 0
Now the only problem left, is the set args=%*.
If you can't control the content, then there is no way to access %* in a simple safe way.
Think of this batch invokations
myBatch.bat "abc|"
myBatch.bat abc^|
myBatch.bat abc^|--"|"
But you could use How to receive even the strangest command line parameters?
or Get arguments without temporary file
Btw. You could spare your child process, you can also exit from a function
Look at Exit batch script from inside a function
One correction to above answers.
Yes, ENDLOCAL is implied at the end of the script, but there's a catch.
I've found that with nested scripts, if you don't ENDLOCAL before you EXIT /B 1 you will not get your return code of 1 at the next level out script.
If you only ever EXIT /B 0, then this will not matter as the default return code is 0.
I am coding a batch file and it needs some more files. But they files should only be able to run using the call function from another batch file. My code looks like this:
call compileData.bat
pause
I want the compilerData.bat just starts when it's called from this one, not if its just started from Explorer or something other.
Can you please help me?
I have tried to find a solution on this problem in a whole hour!
You can use a parameter.
compileData.bat:
if "%1" neq "somestring" exit /b
REM rest of your code
Another.bat:
call compileData.bat somestring
pause
I cannot think of any way that would prevent the bare "run" of the called script. Possibly that might only be done using NTFS permissions.
What you can do quickly is something like this:
MOTHERBATCH.bat
call compileData.bat SomePASSPHRASE
compileData.bat
#echo off
if not "%1"=="SomePASSPHRASE" (
echo "You can not run this script directly, please run MOTHERSCRIPT.bat."
exit /B 1
)
echo "Passphrase is correct, code is executed..."
Set an environment variable in the parent script, then if that variable is not set or doesn't have the correct value in the children, they just exit with an error message explaining they aren't intended for standalone use. You really can't prevent someone from reverse engineering the code and forcing it to run.
You could put the children in a password protected zip file and have the parent unpack it just before calling them. Then when the parent is done, it deletes the unpacked scripts.
Do all of the above.
You can use a not so well known system variable named cmdcmdline.
I will explain a brief usage for you.
For brevity's sake we will have two very simple batch files.
Parent.bat
#echo off
call compiledata.bat
And compiledata.bat
#echo off
echo %cmdcmdline%
pause
When compiledata.bat is executed on its own this variable's value is the batch file itself.
C:\WINDOWS\system32\cmd.exe /c ""C:\Batch\CALL\compiledata.bat" "
But when compiledata.bat is called from parent.bat the variable's value is that of the calling parent.bat.
C:\WINDOWS\system32\cmd.exe /c ""C:\Batch\CALL\parent.bat" "
My suggestion is putting all your batch code into a single batch file and use subroutines. Open a command prompt window and run call /? for help on how to use subroutines which is nothing else than calling a batch file being embedded in current batch file.
A simple example:
#echo off
echo Running %~f0 %*
call :compileData %*
call :WaitForUser
rem The next line results in exiting processing of this batch file
goto :EOF
:compileData
echo/
echo Running subroutine compileData with the arguments: %*
rem Exit processing subroutine compileData and continue above
rem after the command line calling the subroutine compileData.
goto :EOF
:WaitForUser
echo/
pause
rem Exit processing subroutine WaitForUser and continue above
rem after the command line calling the subroutine WaitForUser.
goto :EOF
See also Where does GOTO :EOF return to? And take a look on DosTips forum topic ECHO. FAILS to give text or blank line - Instead use ECHO/ for the explanation on using echo/ to output an empty line.
Here's my solution:
when launched from the command line, %cmdcmdline% inherits the name from the base calling program, so it wouldn't be the name of the "middle man" calling your batch file
this is what I came up with. I had to use the "subroutine" method to get the variables properly expanded
Note: Edge Case: if you use complex paths with the batch files having the same name in different folders, you could run into an "Edge Case". If that is important to you, then you might have to further parse the file names. I'm not totally sure, it wasn't my use case so I didn't go further.
#echo OFF
setlocal EnableDelayedExpansion
call :myGetFileName "%CmdCmdLine%"
if /I "%sRet%"=="%~nx0" (
echo ************** Pause
) else (
echo ************** NO Pause
)
echo finished test
pause
exit
:myGetFileName
set "sRet=%~nx1"
exit /b
I'm making a Minecraft modding tool using a batch file. But on execution of the batch file the Windows command interpreter outputs the syntax error message:
) was unexpected
I can't figure out why.
This is my code:
#echo off
cd mods
setlocal enabledelayedexpansion
set "selected=1"
call:print 1
call:print 2
:menu
choice /c wse>nul
if "%errorlevel%"=="2" (
if not !selected! GEQ !a! (
set /a "selected+=1"
cls
call:print 1
call:print 2
)
)
if "%errorlevel%"=="1" (
if not !selected!==1 (
set /a "selected-=1"
cls
call:print 1
call:print 2
)
)
if "%errorlevel%"=="3" (
)
goto menu
:print
if "%1"=="1"set a=0
echo.
if "%1"=="1" (
echo Uninstalled:
) else (
echo Installed:
)
echo.
for %%f in (*.jar) do (
if "%1"=="1" (
if NOT EXIST
"C:/Users/Coornhert/AppData/Roaming/.minecraft/mods/%%~nf.jar" (
set /a "a+=1"
if "!a!"=="!selected!" (
echo -%%~nf
) else (
echo %%~nf
)
set "b=!a!"
)
) else (
if EXIST "C:/Users/Coornhert/AppData/Roaming/.minecraft/mods/%%~nf.jar" (
set /a "a+=1"
if "!a!"=="!selected!" (
echo -%%~nf
) else (
echo %%~nf
)
set "b=!a!"
)
)
)
goto :eof
And it works, but when I hit s, execution terminates with the error message.
Folder structure of folder containing the batch file:
mods
Foo.jar
Foo2.jar
Folder structure of target folder:
C:\Users\Coornhert\AppData\Roaming\.minecraft\mods
Foo.jar
I partly do not understand what this batch file should do, but here is the batch file rewritten with several improvements.
#echo off
setlocal EnableExtensions EnableDelayedExpansion
rem cd /D "%~dp0mods"
pushd "%~dp0mods"
set "a=0"
set "selected=1"
call :PrintIt 1
call :PrintIt 2
:Menu
choice /C wse /N
if errorlevel 3 popd & endlocal & goto :EOF
if errorlevel 2 goto AddOne
if %selected% == 1 goto Menu
set /A selected-=1
cls
call :PrintIt 1
call :PrintIt 2
goto Menu
:AddOne
if %selected% GEQ %a% goto Menu
set /A selected+=1
cls
call :PrintIt 1
call :PrintIt 2
goto Menu
:PrintIt
if %1 == 1 set "a=0"
echo/
if %1 == 1 (echo Uninstalled:) else echo Installed:
echo/
for %%I in (*.jar) do (
if %1 == 1 (
if not exist "%APPDATA%\.minecraft\mods\%%~nI.jar" (
set /A a+=1
if !a! == %selected% (echo -%%~nI) else echo %%~nI
set "b=!a!"
)
) else (
if exist "%APPDATA%\.minecraft\mods\%%~nI.jar" (
set /A a+=1
if !a! == %selected% (echo -%%~nI) else echo %%~nI
set "b=!a!"
)
)
)
goto :EOF
It does nothing useful as is, but batch code in question is also not useful at all.
The applied improvements are:
The command SETLOCAL is moved to top of file. The reason is:
It pushes path of current directory on stack.
It pushes state of command extensions on stack.
It pushes state of delayed expansion on stack.
It pushes the memory address of the current environment variables table on stack.
It creates a copy of the current environment variables table in memory and makes this new environment variables table active.
It sets command extensions and delayed expansion according to the specified parameters if the command is called with parameters at all.
The command ENDLOCAL is executed before leaving batch file. The reason is:
It deletes the current environment table which means no environment variable defined in this batch file exists anymore after ENDLOCAL except it existed already before execution of command SETLOCAL.
It pops memory address of previous environment table from stack and uses this address resulting in restoring initial environment variables.
It pops state of delayed expansion from stack and disables/enables delayed expansion accordingly.
It pops state of command extensions from stack and disables/enables command extensions accordingly.
It pops previous current directory path from stack and sets current directory to this path to restore the current directory.
So the entire command process environment is restored on exit of this batch file to exactly the same environment as it was on starting the batch file.
This makes it possible to call this batch file from within another batch file or from within a command prompt window with no impact on calling batch file or command process.
The command CD could be extended to include drive and path of argument 0 which is the full path of the batch file ending with a backslash because the subdirectory mods is most likely always expected in directory of the batch file and it should not matter what is the current directory on running the batch file.
But cd /D "%~dp0mods" could fail if the batch file is located on a network share accessed using UNC path and therefore command PUSHD is used instead working with enabled command extensions also for UNC paths.
In all programming and scripting languages it is required that variables are defined and initialized with a value before being used the first time. For that reason the environment variables a and selected are defined at top of the batch file with default values. By the way: a is a very bad name for a variable. Why? Search for a in batch file. It is quite often found on not using special find features like whole word only, isn't it.
PRINT is a command as it can be seen on running in a command prompt window print /?. While it is possible to use command names as labels or as names for subroutines, it is not advisable to do so as it could be confusing for readers of the batch file.
The command CHOICE has the option /N to hide the list of choices in the prompt. It is better to use this option than redirecting the output of CHOICE to device NUL.
The very old but still valid Microsoft support article Testing for a Specific Error Level in Batch Files explains that if errorlevel X means that the condition is true if the exit code of previous command or application is greater or equal X. The command CHOICE with 3 choices exits always with 1, 2 or 3 as exit code. So it is best to use:
if errorlevel 3 rem Do something on third choice avoiding fall through to next line.
if errorlevel 2 rem Do something on second choice avoiding fall through to next line.
Do something on first choice.
The advantage of using this method is that it even works with CHOICE within a command block on which if %ERRORLEVEL% == X fails because of delayed expansion would be required and usage of if !ERRORLEVEL! == X.
The integer comparison if %selected% GEQ %a% would not work if the two arguments would be enclosed in double quotes as the double quotes are also interpreted as part of the arguments to compare. For that reason using if "%selected%" GEQ "%a%" would result in running a string comparison instead of an integer comparison. For more information about comparing values with IF look on answer on Exit a for loop in batch.
It is safe here to omit the double quotes also on the other IF conditions with == operator running string comparisons because the environment variables selected and a must be both defined before running this IF condition and therefore both variables are defined at top of the batch file.
The answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line? explains why set "variable=value" should be always used to assign a value to an environment variable or delete an environment variable on omitting the value. And this answer also explains why on set /A variable=expression the double quotes can be usually omitted as whitespace characters are interpreted completely different within an arithmetic expression. The exception is usage of set /A with 1 or more commands on same command line on which double quotes around variable=expression would be also needed.
The batch file should be exited when the batch file user enters e or E to take third choice. This could be done with just goto :EOF, or with exit /B which is an alias for goto :EOF, or with just exit which always exits entire command process independent on calling hierarchy which is not recommended. Windows command interpreter would implicitly restore the initial stack before finishing batch file execution. But it is nevertheless good coding practice to pop from stack with code which was pushed on stack before with code. For that reason there is used popd & endlocal & goto :EOF. See answer on Single line with multiple commands using Windows batch file for more information about usage of multiple commands on one command line.
The list of predefined environment variables of used user account is output on running in a command prompt window the command set. One predefined Windows environment variable is APPDATA with path to application data of current user account. This environment variable should be used instead of a fixed path to application data directory of user account.
And the directory separator on Windows is the backslash character \ and not slash character / as on Unix and Mac.
The usage of f as loop variable is not recommended as this is also a loop variable modifier. %%~f can be interpreted by Windows command interpreter as value of loop variable f without surrounding double quotes or as incomplete loop variable reference because of missing loop variable after %%~f which could be also interpreted as full file name of ?. So it is better to use # or $ as loop variable or upper case letters to avoid such a confusion on interpreting the loop variable reference. Loop variables are case-sensitive.
I prefer for IF conditions with an ELSE branch the coding style
if condition (
command
) else (
command
)
But here in this batch file with command being just a short ECHO command the code is better readable on being more compact with using:
if condition (echo short message) else echo other short message
Delayed expansion for an environment variable referenced within a command block started with ( and ending with matching ) is only needed if the environment variable is also modified in same command block. Therefore environment variable a must be referenced in body of FOR with usage of delayed expansion while environment variable selected can be referenced as usual because of not modified within this command block at all.
It is better to use echo/ to output an empty line instead of echo.. For the reason read the DosTips forum topic: ECHO. FAILS to give text or blank line - Instead use ECHO/
For a basic understanding of the used commands, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
choice /?
cls /?
echo /?
endlocal /?
for /?
goto /?
if /?
popd /?
pushd /?
rem /?
set /?
setlocal /?
I have a simple function written to check for directories:
:direxist
if not exist %~1 (
echo %~1 could not be found, check to make sure your location is correct.
goto:end
) else (
echo %~1 is a real directory
goto:eof
)
:end is written as
:end
endlocal
I don't understand why the program would not stop after goto:end has been called. I have another function that uses the same method to stop the program and it work fine.
:PRINT_USAGE
echo Usage:
echo ------
echo <file usage information>
goto:end
In this instance, the program is stopped after calling :end; why would this not work in :direxist? Thank you for your help!
I suppose you are mixing call and goto statements here.
A label in a batch file can be used with a call or a goto, but the behaviour is different.
If you call such a function it will return when the function reached the end of the file or an explicit exit /b or goto :eof (like your goto :end).
Therefore you can't cancel your batch if you use a label as a function.
However, goto to a label, will not return to the caller.
Using a synatx error:
But there is also a way to exit the batch from a function.
You can create a syntax error, this forces the batch to stop.
But it has the side effect, that the local (setlocal) variables will not be removed.
#echo off
call :label hello
call :label stop
echo Never returns
exit /b
:label
echo %1
if "%1"=="stop" goto :halt
exit /b
:halt
call :haltHelper 2> nul
:haltHelper
()
exit /b
Using CTRL-C:
Creating an errorcode similar to the CTRL-C errorcode stops also the batch processing.
After the exit, the setlocal state is clean!
See #dbenham's answer Exit batch script from inside a function
Using advanced exception handling:
This is the most powerful solutions, as it's able to remove an arbitrary amount of stack levels, it can be used to exit only the current batch file and also to show the stack trace.
It uses the fact, that (goto), without arguments, removes one element from the stack.
See Does Windows batch support exception handling?
jeb's solution works great. But it may not be appropriate in all circumstances. It has 2 potential drawbacks:
1) The syntax error will halt all batch processing. So if a batch script called your script, and your script is halted with the syntax error, then control is not returned to the caller. That might be bad.
2) Normally there is an implicit ENDLOCAL for every SETLOCAL when batch processing terminates. But the fatal syntax error terminates batch processing without the implicit ENDLOCAL! This can have nasty consequences :-( See my DosTips post SETLOCAL continues after batch termination! for more information.
Update 2015-03-20 See https://stackoverflow.com/a/25474648/1012053 for a clean way to immediately terminate all batch processing.
The other way to halt a batch file within a function is to use the EXIT command, which will exit the command shell entirely. But a little creative use of CMD can make it useful for solving the problem.
#echo off
if "%~1" equ "_GO_" goto :main
cmd /c ^""%~f0" _GO_ %*^"
exit /b
:main
call :label hello
call :label stop
echo Never returns
exit /b
:label
echo %1
if "%1"=="stop" exit
exit /b
I've got both my version named "daveExit.bat" and jeb's version named "jebExit.bat" on my PC.
I then test them using this batch script
#echo off
echo before calling %1
call %1
echo returned from %1
And here are the results
>test jebExit
before calling jebExit
hello
stop
>test daveExit
before calling daveExit
hello
stop
returned from daveExit
>
One potential disadvantage of the EXIT solution is that changes to the environment are not preserved. That can be partially solved by writing the environent to a temporary file before exiting, and then reading it back in.
#echo off
if "%~1" equ "_GO_" goto :main
cmd /c ^""%~f0" _GO_ %*^"
for /f "eol== delims=" %%A in (env.tmp) do set %%A
del env.tmp
exit /b
:main
call :label hello
set junk=saved
call :label stop
echo Never returns
exit /b
:label
echo %1
if "%1"=="stop" goto :saveEnvAndExit
exit /b
:saveEnvAndExit
set >env.tmp
exit
But variables with newline character (0x0A) in the value will not be preserved properly.
If you use exit /b X to exit from the function then it will set ERRORLEVEL to the value of X. You can then use the || conditional processing symbol to execute a command if ERRORLEVEL is non zero.
#echo off
setlocal
call :myfunction PASS || goto :eof
call :myfunction FAIL || goto :eof
echo Execution never gets here
goto :eof
:myfunction
if "%1"=="FAIL" (
echo myfunction: got a FAIL. Will exit.
exit /b 1
)
echo myfunction: Everything is good.
exit /b 0
Output from this script is:
myfunction: Everything is good.
myfunction: got a FAIL. Will exit.
Here's my solution that will support nested routines if all are checked for errorlevel
I add the test for errolevel at all my calls (internal or external)
#echo off
call :error message&if errorlevel 1 exit /b %errorlevel%<
#echo continuing
exit /b 0
:error
#echo in %0
#echo message: %1
set yes=
set /p yes=[no]^|yes to continue
if /i "%yes%" == "yes" exit /b 0
exit /b 1