Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bat file and labels

Tags:

batch-file

cmd

I am trying to write a bat file for a network policy that will install a program if it doesn't exist as well as several other functions. I am using GOTO statements depending on whether or not certain criterion are met. However, it seems that the labels are not firing correctly as all of them do.

I have simplified my script so as to grasp some idea of what may be happening.

@echo off


IF EXIST c:\test\test.txt (GOTO :EXISTING) ELSE GOTO :MISSING

:EXISTING
echo file exists

:MISSING
echo file missing

ping localhost -n 5 >NUL

Basically it checks to see that the file "test.txt" exists in folder "c:\test" which id does. So it should echo file exists to the console. However, both "file exists" and "file missing" are echoed to the console. I find that if I remove the file from the folder or simply rename it, it only echoes "file missing"

Why is it running running both labels?

like image 232
cameron213 Avatar asked Dec 12 '22 18:12

cameron213


1 Answers

Because a GOTO is just a jump in execution to a point in the script, then execution continues sequentially from that point. If you want it to stop after running 'EXISTING', then you need to do something like this. Note the extra GOTO and new label:

@ECHO OFF
IF EXIST c:\test\test.txt (GOTO :EXISTING) ELSE GOTO :MISSING

:EXISTING
echo file exists
goto :NEXTBIT

:MISSING
echo file missing

:NEXTBIT
ping localhost -n 5 >NUL

It's worth noting though that with cmd.exe (i.e., the NT-based command shells [NT, Win2k, XP, etc]), you can do IF...ELSE blocks like this:

@ECHO OFF
IF EXIST c:\test\test.txt (
    ECHO File exists
) ELSE (
    ECHO File missing
)
ping localhost -n 5 >nul

...so you can eliminate your GOTOs entirely.

like image 169
Chris J Avatar answered Mar 08 '23 00:03

Chris J