Skip to main content

Batch Script Debugging

Batch Script Debugging

Debugging is important because it allows to discover and to fix errors in a program before releasing it to the public.

As in any programming language, debugging is also possible in batch scripts.

You can debug in different ways:

  • Using echo command
  • Using pause command
  • Logging the error messages to another file
  • Using ErrorLevel to detect errors and log them

Using echo command

The easiest way to debug is to use the echo command in batch scripts.

It will display the message in the command prompt and help you debug where things have gone wrong.

In the following example

@echo off  
if [%1] == [] (
echo input value not provided
goto stop
rem Display numbers
for /l %%n in (2,2,%1) do (
echo %%n
Press any key to continue ...

Using pause command

Another way is to pause batch execution when an error occurs. When the script is paused, the developer can fix the problem and restart processing.

In the following example, the batch script is paused because the input value is mandatory and is not provided.

@echo off  
if [%1] == [] (
echo input value not provided
goto stop
) else (
echo "Valid value"
input value not provided
Press any key to continue..

Logging the error messages to another file

It may be difficult to debug the error just by looking at a bunch of echoes displayed in the command prompt. Another simple solution is to record the messages in another file and view them step by step to understand what went wrong.

For example, the command given in the .bat file is wrong:

net statistics /Server

so we can log it and then see what we get:

C:\>example-log.bat > testlog.txt 2> testerrors.txt

The file testerrors.txt will display the error messages as shown below:

The option /SERVER is unknown.
The syntax of this command is:
More help is available by typing NET HELPMSG 3506.

Looking at the testlog.txt and testerrors.txt files the developer can fix the program and execute again.

Using ErrorLevel to detect errors and log them

Errorlevel returns 0 if the command executes successfully and 1 if it fails.

Consider the following example:

@echo off
if errorlevel 1 GOTO stop
echo Unable to connect to

During execution, you can see errors as well as logs:

C:\>example-errorelevel.bat > testlog.txt

And the output is inside the textlog.txt file:

Pinging [] with 32 bytes of data:
Reply from bytes=32 time=160ms TTL=111
Reply from bytes=32 time=82ms TTL=111
Reply from bytes=32 time=121ms TTL=111
Reply from bytes=32 time=108ms TTL=111
Ping statistics for
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 82ms, Maximum = 160ms, Average = 117ms
Connected successfully
Press any key to continue . . .

In case of failure, you will see the following logs inside testlog.txt.

Ping request could not find host Please check the name and try again.
Unable to connect to
Press any key to continue . . .