Sequence loops and jump labels batch file: loop goto

Diese Seite gibt es auch in Deutsch

Jump marks:

Example:

@echo off
goto jump
echo hello
:jump
echo jumped
pause

Output:

jumped

(echo hello is ignored because the command "goto jump" skips the line "echo hello").

TEST: does a file exist?

if exist %file.txt
Example:

@echo off
if exist %file.txt goto fileexists
echo File not found!
goto END
:fileexists
echo File exists!
:END 
pause 

Output: if file file.txt exists: "file exists!" if file file.txt does not exist: "File not found!"

Errorlevel:

each command returns certain errorlevel:
mostly errorlevel 1 means that the command was not successful:
example:

@echo off
xcopy c:\so c:\so2
if errorlevel 1 goto error
goto ende
:error
echo das kopieren war nicht erfolgreich!
:ende
pause

in this example the directory c:\so is copied to c:\so2,
if now e.g. so does not exist, the batch file writes: "the copy was not successful!"

for loop

For %%f In (c:\batch\*.bat c:\bat\*.bat) Do Copy %%f 

explanation: this line copies all files in the folder c:\batch with file extension .bat to c:\bat

 the counter can also look like this

for /l %i in (1,1,100) do echo %i

means: starting from 1 in steps of 1 up to 100; executed is echo %i (%i is the sequential number)

if

if "alle"=="%1" del *.tmp 

Explanation: %1 is a variable attached to the batch file when called:
e.g. batchfile.cmd variable. So if in this example "all" is appended to the batch file: batchfile.cmd all, then all files with extension .tmp will be deleted from the current directory.

Also possible would be a query with if not 1==2 ... (so if 1 is not 2 is true in this case)

wait for task

:LOOP
echo in der Schleife
@ping -n 10 localhost> nul
TaskList|Find "Taskname" >NUL || If Errorlevel 1 Goto WEITER
Goto LOOP
:WEITER

Explanation:
with "@ping -n 10 localhost> nul" is waited in the loop 10 seconds,
the command line "TaskList|Find "Taskname" >NUL || If Errorlevel 1 Goto CONTINUE" leaves the loop only, if the Task: "Taskname" does not run any longer

advanced topics

positive Bewertung({{pro_count}})
Rate Post:
{{percentage}} % positive
negative Bewertung({{con_count}})

THANK YOU for your review!

Publication: 2022-11-04 from Bernhard 🔔


Top articles in this section


sleep or wait in batch files: pause cmd
The function wait or sleep was not available in BATch files by default.Remedy is a small detour via the ping Command

Structure of a batch file Syntax: echo off cmd
If you have created a batch file, you can write a command in each line, see: how to create a batch file - basics. The commands are executed in sequence when the file is started. The behavior of the output can be adjusted as follows:

Practical examples with batch
Handling variables in Windows Batch (command prompt) Read all variables Variables can be read out in the command prompt with the set command:

Questions / Comments