Coding⏱️ 3 min read📅 2026-06-15

How to Fix: Error handling in Batch script when a batch script failed

Error handling in Batch script when a batch script fails

Quick Answer: The issue is caused by the fact that the `errorlevel` variable is not reset after the `call` command. To fix this, use the `setlocal` command to create a new environment for the called batch file and then check its exit code.

The error described occurs when running a batch script that calls another batch script, and the called script fails. The main issue is that the outer batch script prints both 'Sync failed' and 'Sync success', indicating an inconsistent behavior.

This inconsistency can be frustrating for users who rely on this specific output format. In this troubleshooting guide, we will explore the root causes of this error and provide two primary fix methods to resolve it.

🛑 Root Causes of the Error

  • The primary reason for this error is that the 'errorlevel' command in batch scripting does not work as expected when used with the 'call' command. When a called script fails, its error level is not properly propagated to the outer script.
  • Another possible cause is that the 'cmd /k' command in the 'ERROR' section of the script is causing an unexpected behavior. The '/k' option executes the command and returns to the previous command prompt, which can lead to inconsistent output.

🚀 How to Resolve This Issue

Modify the batch script to use a different method for checking error levels

  1. Step 1: Replace the 'call get_files.bat' line with 'call get_files.bat && if %errorlevel% neq 0 goto ERROR'. This will ensure that the outer script only executes the called script if it returns a non-zero exit code.
  2. Step 2: Modify the 'ERROR' section to use 'if %errorlevel% == 1 goto ERROR', which checks for a specific error level (in this case, 1) instead of relying on an inconsistent behavior.
  3. Step 3: Save and re-run the batch script to test the changes.

Use a different approach with cmd /k

  1. Step 1: Modify the 'ERROR' section to use 'call get_files.bat > output.txt && if exist output.txt goto ERROR'. This will redirect the output of the called script to a file and check if it exists before executing further.
  2. Step 2: Replace the 'cmd /k' command with 'echo Sync failed', which directly prints the desired output without causing an unexpected behavior.
  3. Step 3: Save and re-run the batch script to test the changes.

🎯 Final Words

To resolve the error of printing both 'Sync failed' and 'Sync success' when a batch script calls another successful script, modify the batch script to use one of the two provided fix methods. By making these changes, you can ensure consistent output and avoid this frustrating issue.

Did this fix your problem?

If not, try searching for specific error codes.

🔍 Search Error Database

❓ Frequently Asked Questions