How to have a called batch file halt the parent [duplicate] - windows

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

Related

Check if file is locked inside a batch file for loop

I have a script that runs through some files and copies them to another location. But the script needs to wait until the file is no longer being written to.
I tried all the solutions here:
How to check in command-line if a given file or directory is locked (used by any process)?
Process a file after a file is finished being written Windows Command Line .bat
BATCH - wait for file to be complete before picking up
But the problem is that they don't work when wrapped in a loop. It always says the file is locked. If the script it cancelled and re-run it correctly finds the file unlocked.
Am I doing something wrong or is there a trick to make this work?
For locking a test file, checkfile.txt, I do:
(
>&2 pause
) >> checkfile.txt
Then the example script to check the file is this:
#echo off
for %%i in (*.txt) do (
:loop
ping localhost -n 5 > nul
echo "check if locked"
powershell -Command "$FileStream = [System.IO.File]::Open('%%i', 'Open', 'Write'); $FileStream.Close(); $FileStream.Dispose()" >NUL 2>NUL || (goto :loop)
echo "NOT locked anymore"
)
You cannot goto in a loop as it will simply break the for loop entirely. Additionally, the exit code or errorlevel is set for the last successful command. In this case being the powershell dispose command. Simply do the loop outside of the code block:
#echo off & setlocal
for %%i in (*.txt) do call :loop %%~i
goto :EOF
:loop
powershell -Command "[System.IO.File]::Open('%1', 'Open', 'Write')">nul 2>&1 && echo %1 not locked || (
echo %1 Locked
("%systemroot%\system32\timeout.exe" /t 3)>nul
goto :loop
)
Note, the conditional operators (and &&) and (or ||) helps to evaluate the exit code without needing to do if and else statements.

Execute batch code when user click on exit

I am working on some code testing, and I stumbled on a problem I can't find or fix. My problem is:
If a user accidentally closes the cmd window, I'd like to execute a batch code before it actually closes. For example:
I run script A.bat . When a user wants to exit, I want it to delete my B.bat and then close the window.
This is how the code may look like:
#ECHO OFF
echo Welcome to A.bat
del B.bat (when user exits the window)
I couldn't find it on google and forums, so I thought maybe you guys could help me out. Thanks in advance, Niels
This works for me:
#ECHO OFF
if "%1" equ "Restarted" goto %1
start "" /WAIT /B "%~F0" Restarted
del B.bat
goto :EOF
:Restarted
echo Welcome to A.bat
echo/
echo Press any key to end this program and delete B.bat file
echo (or just close this window via exit button)
pause
exit
EDIT: Some explanations added
The start command restart the same Batch file in a new cmd.exe session; the /B switch open it in the same window and the /WAIT switch makes the original file to wait until the new one ends. The new Batch file must end with exit in order to kill the new cmd.exe session (because it was started with the /K switch). No matters if the new cmd.exe session ends normally because the exit command or because it was cancelled with the red X; in any case the control returns after the line that started it in the original execution.
I've had to do something similar to what you're describing. I'm not sure whether this is the simplest or most efficient way to accomplish what you ask, but it does indeed work nevertheless.
#echo off
setlocal
:lockFile
rem // create lock file to inform forked helper thread when this thread completes
rem // credit to dbenham: http://stackoverflow.com/a/27756667/1683264
set "lockFile=%temp%\%~nx0_%time::=.%.lock"
9>&2 2>NUL (2>&9 8>"%lockFile%" call :main %*) || goto :lockFile
del "%lockFile%"
exit /b
:main
call :cleanup_watcher "B.bat"
rem // put your main script here
pause
goto :EOF
:cleanup_watcher <file> (<file> <file> etc.)
rem // Write external script to delete filename arguments
rem // (so if main script exits via ^C, temp files are still removed)
>"%temp%\tmp.bat" (
echo #echo off
echo setlocal
echo :begin
echo ping -n 1 -w 500 169.254.1.1 ^>NUL
echo del /q "%temp%\%~nx0*.lock" ^>NUL 2^>NUL
rem // If lockfile can't be deleted, the main script is still running.
echo if exist "%temp%\%~nx0*.lock" goto :begin
echo del /q "%temp%\tmp.bat" %* ^&^& exit
)
rem // fork cleanup watcher invisibly to catch ^C
>"%lockfile%.vbs" echo CreateObject("Wscript.Shell").Run "%temp%\tmp.bat", 0, False
wscript "%lockfile%.vbs"
del "%lockfile%.vbs"

Batch files can not supress "terminate job"

Im trying to open a 2nd batch file and detect if it normally exited or closed by a user (ctrl+c or x or window termiate etc..)
so Im using this following example by Batch run script when closed
#Echo off
set errorlevel=1
start /w %comspec% /c "mode 70,10&title Folder Confirmation Box&color 1e&echo.&echo. Else the close window&pause>NUL&exit 12345"
echo %errorlevel%
pause
Im trying to keep 1st batch waiting (/W) since I will check for errorlevel later on
But after closing the 2nd batch file I get an error like ^cterminate batch job (Y/N)?
I tried the suggestion over https://superuser.com/questions/35698/how-to-supress-terminate-batch-job-y-n-confirmation
with the script
rem Bypass "Terminate Batch Job" prompt.
if "%~2"=="-FIXED_CTRL_C" (
REM Remove the -FIXED_CTRL_C parameter
SHIFT
) ELSE (
REM Run the batch with <NUL and -FIXED_CTRL_C
CALL <NUL %1 -FIXED_CTRL_C %*
GOTO :EOF
)
That works quite fine
So is there a way of starting from same batch file and avoiding the terminating?
Or do I have to create a new batch from same batch and call it?
(I don't want them to see the file aswell)
Do not assign values to a volatile environment variable like errorlevel using set command. Doing that causes it becomes unvolatile in current context.
Always use title in START "title" [/D path] [options] "command" [parameters].
start "" /W cmd /c "anycommand&exit /B 12345" always returns 12345 exit code. It's because all the cmd line with & concatenated commands is prepared in parsing time (the same as a command block enclosed in parentheses) and then run entirely, indivisibly. Omit &exit /B 12345 to get proper exit code from anycommand, or replace it with something like start "" /W cmd /c "anycommand&&exit /B 12345||exit /B 54321" to get only success/failure indication.
Next code snippet could help:
#ECHO OFF
SETLOCAL enableextensions
set "_command=2nd_batch_file.bat"
:: for debugging purposes
set "_command=TIMEOUT /T 10 /NOBREAK"
:: raise errorlevel 9009 as a valid file name can't contain a vertical line
invalid^|command>nul 2>&1
echo before %errorlevel%
start "" /w %comspec% /C "mode 70,10&title Folder Confirmation Box&color 1e&echo(&echo( Else the close window&%_command%"
echo after %errorlevel%
Output shows sample %_command% exit codes: 0 or 1 if came to an end properly but -1073741510 if terminated forceably by Ctrl+C or Ctrl+Break or red ×
==>D:\bat\SO\31866091.bat<nul
before 9009
after 0
==>D:\bat\SO\31866091.bat<nul
before 9009
after 1
==>D:\bat\SO\31866091.bat<nul
before 9009
^CTerminate batch job (Y/N)?
after -1073741510
==>
This works for me:
call :runme start /w "Child Process" %comspec% /c "child.bat & exit 12345" <NUL >NUL 2>NUL
echo %ERRORLEVEL%
goto :eof
:runme
%*
goto :eof
The idea is to call a subroutine in the current script rather than calling out to an external script. You can still redirect input and output for a subroutine call.

How do I detect if script was CALL'ed or invoked directly, in Windows CMD.EXE shell?

I need to distinguish these two situations inside script.cmd:
C:\> call script.cmd
C:\> script.cmd
How can I determine if my script.cmd was invoked directly, or invoked in the context of using a CALL?
If it matters, this is on Windows 7.
#echo off
set invoked=0
rem ---magic goes here---
if %invoked%==0 echo Script invoked directly.
if %invoked%==1 echo Script invoked by a CALL.
Anyone know the "magic goes here" which would detect having been CALL'ed and set invoked=1?
At this moment, I see no way to detect it, but as a workaround you can always force the use of the sentinel.
#echo off
setlocal enableextensions
rem If "flag" is not present, use CALL command
if not "%~1"=="_flag_" goto :useCall
rem Discard "flag"
shift /1
rem Here the main code
set /a "randomExitCode=%random% %% 2"
echo [%~1] exit with code %randomExitCode%
exit /b %randomExitCode%
goto :eof
rem Retrieve a correct full reference to the current batch file
:getBatchReference returnVar
set "%~1=%~f0" & goto :eof
rem Execute
:useCall
setlocal enableextensions disabledelayedexpansion
call :getBatchReference _f0
endlocal & call "%_f0%" _flag_ %*
This will allow you to use the indicated syntax
script.cmd first && script.cmd second && script.cmd third
The posted code ends the script with a random exit code for testing. Execution will continue when the exit code is 0
NOTE: For it to work, at least in XP, it seems the call to the batch file MUST be the last code in the batch file
Check if the script's path is in the CMDCMDLINE variable. If not, then it was probably called.
In this example I use %CMDCMDLINE:"=/% to turn the quotes into forward-slashes (the FIND command can't search for quotes) and I echo it with <NUL SET/P="" so that certain characters in the file path (like ampersands) don't break the script.
<NUL SET/P="%CMDCMDLINE:"=/%" | FIND "/%~0/">NUL || (
REM Commands to perform if script was called
GOTO:EOF
)
::AND/OR
<NUL SET/P="%CMDCMDLINE:"=/%" | FIND "/%~0/">NUL && (
REM Commands to perform if script was NOT called
GOTO:EOF
)

Variable not getting set correctly in a dos batch file on XP

I am trying to write a batch file to be run in a command prompt on XP. I am trying to get a listing of files in a specific path that follow a certain naming convention. I need to copy and rename each file instance to a static name and drop it to a transmission folder.
Since it may take a little while for the file to go in the transmission folder, I need to check before I copy the next file over so that I don't overlay the previous file. I am not able to use SLEEP or TIMEOUT since I don't have the extra toolkit installed. I try to just continually loop back to a START section until the file is sent.
I noticed that if I passed the %%x value set in the for loop that if I loop back to the START section a couple of times, it seems to lose its value and it is set to nothing. So I tried to set a variable to hold the value.
I seem to be having issues with the variable not being set correctly or not cleared. Originally it kept on referencing the first file but now it doesn't seem to be set at all. The ECHO displays the correct the value but the filename variable is empty still.
Does anyone know a better way of doing this? Thanks in advance for your help as I have already wasted a whole day on this!
This is the batch file:
#ECHO "At the start of the loop"
#for %%x in (C:\OUTBOUND\customer_file*) do (
#ECHO "In the loop"
#ECHO "loop value ="
#ECHO %%x
SET filename=%%x
#ECHO "filename ="
#ECHO %filename%
#ECHO ...ARCHIVE OUTBOUND CUSTOMER FILE
archivedatafile --sourcefile="%filename%" --archivefolder="..\archivedata\customer" --retentiondays=0
IF NOT %ERRORLEVEL%==0 GOTO ERROR
PAUSE
:START
IF EXIST l:\OutputFile (
#ping 1.1.1.1 -n 1 -w 30000
GOTO START
) ELSE (
COPY %filename% l:\OutputFile /Y
IF NOT %ERRORLEVEL%==0 GOTO ERROR
PAUSE
)
)
GOTO END
:ERROR
#echo off
#ECHO *************************************************************
#ECHO * !!ERROR!! *
#ECHO *************************************************************
:END
SET filename=
foxidrive has provided a script that should work, but did not provide an explanation as to why your code fails and how he fixed the problems.
You have 2 problems:
1) Your FOR loop is aborted immediately whenever GOTO is executed within you loop. It does not matter where the GOTO target label is placed - GOTO always terminates a loop. Foxidrive's use of CALL works perfectly - the loop will continue once the CALLed routine returns.
2) You attempt to set a variable within a block of code and then reference the new value within the same block. %VAR% is expanded when the statement is parsed, and complicated commands like IF and FOR are parsed once in their entirety in one pass. Actually, any block of code within parentheses is parsed in one pass. So the values of %ERRORLEVEL% and %FILENAME% will be constant - the values that existed before the block was entered.
As Endoro has indicated, one way to solve that problem is to use delayed expansion. Delayed expansion must be enabled by using setlocal enableDelayedExpansion, and then expand the variable using !VAR!. The value is expanded at execution time instead of parse time. Type HELP SET from the command prompt for more information about delayed expansion.
But beware that delayed expansion can cause its own problems when used with a FOR loop because the delayed expansion occurs after the FOR variable expansion: %%x will be corrupted if the value contains a !. This problem can be solved by carefully toggling delayed expansion ON and OFF as needed via SETLOCAL and ENDLOCAL.
Foxidrive's code avoids the entire delayed expansion issue by using CALL. His :NEXT routine is not inside a FOR loop, so all the commands are reparsed each time it is called, so delayed expansion is not required.
This may work - it is untested:
#echo off
ECHO Starting...
for %%x in (C:\OUTBOUND\customer_file*) do call :next "%%x"
echo done
pause
goto :eof
:next
ECHO ...ARCHIVING OUTBOUND CUSTOMER FILE "%~1"
archivedatafile --sourcefile="%~1" --archivefolder="..\archivedata\customer" --retentiondays=0
IF ERRORLEVEL 1 GOTO :ERROR
:loop
echo waiting for file...
ping -n 6 localhost >nul
IF EXIST l:\OutputFile GOTO :loop
COPY "%~1" l:\OutputFile /Y
IF ERRORLEVEL 1 GOTO :ERROR
GOTO :EOF
:ERROR
ECHO *************************************************************
ECHO * !!ERROR!! in "%%x"
ECHO *************************************************************
pause
goto :EOF
try this:
#echo off&setlocal
for %%x in (C:\OUTBOUND\customer_file*) do SET "filename=%%x"
ECHO %filename%
ECHO ...ARCHIVE OUTBOUND CUSTOMER FILE
archivedatafile --sourcefile="%filename%" --archivefolder="..\archivedata\customer" --retentiondays=0
IF NOT %ERRORLEVEL%==0 GOTO:ERROR
PAUSE
:START
IF EXIST l:\OutputFile ping 1.1.1.1 -n 1 -w 30000&GOTO:START
COPY "%filename%" l:\OutputFile /Y
IF NOT %ERRORLEVEL%==0 GOTO:ERROR
PAUSE
GOTO:END
:ERROR
echo off
ECHO *************************************************************
ECHO * !!ERROR!! *
ECHO *************************************************************
:END
SET "filename="
If you use codeblocks (if and for with ( )) and variables with changing values you have to enable delayed expansion. You don't need code blocks in this code, as you can see.

Resources