Eli Richardson
Eli Richardson

Reputation: 930

How to exit batch processing at beginning of a batch file when a file already exists?

I have a batch file and my goal is to use it only once. On further executions this batch file should do nothing. To solve this task, I decided to use If Exist to check for a file created at the end of the batch script. So at the very beginning I have this (I go to the correct directory):

If Exist "file.txt" (
goto exit
)

I set an exit marker at the end of the file.

Alternate methods will be appreciated but I'd prefer the solution to this problem.

Upvotes: 3

Views: 318

Answers (2)

Mofi
Mofi

Reputation: 49096

Microsoft explains for GOTO the possibility to use

goto :EOF

to exit processing of a batch file or a batch subroutine whereby the label EOF (End Of File) is predefined and must not be explicitly defined in batch file.

Another method to exit processing of a batch file or a batch subroutine is using the command EXIT with parameter /B, i.e.

exit /B

This exits just the batch processing and not entire command process which makes a difference on using EXIT for exiting a batch subroutine or when batch file is called from another batch file.

So it can be used for this task either

if exist "file.txt" goto :EOF

or

if exist "file.txt" exit /B

Both lines result on exiting current batch processing and return to calling process which is the command process itself when the batch file was called directly resulting in exiting the command process, too.

Upvotes: 5

sjsam
sjsam

Reputation: 21965

The goto manual says :

Direct a batch program to jump to a labelled line.

Syntax GOTO label

I guess the label(I would not use the term marker) name should not be exit as a windows command exists with the same name. Change the label to

:exitprocess

and do

if exist "file.txt" goto exitprocess

However, if you wish to use exit as a label the workaround is to use

if exist "file.txt" goto :exit

Mind the colon, this is tell goto to find the label named exit

Courtesy : @somethingdark for the workaround.

Upvotes: 5

Related Questions