Skip to content

Batch file continue after error: why ‘rem’ lines fail and the fix

By Updated 13 min read

On this page (8 sections)
  1. The short version
  2. Why batch files stop at errors and 'rem' lines
  3. How to keep a batch file running after an error occurs
  4. Using exit /b to control subroutine errors
  5. Isolating errors with cmd /c and call
  6. Delayed expansion and why 'rem' lines can trigger a halt
  7. Logging errors without halting the script
  8. Questions people still ask

In short: Add setlocal enabledelayedexpansion at the start and wrap critical commands in call statements, or use cmd /c to run commands in a subshell. Append || rem after commands where you want execution to continue despite errors, or check %errorlevel% and decide what happens next.

Part of our guide on fix audio driver windows 11

Most batch files don't halt on errors at all—they keep running with the failure buried in errorlevel until a later command checks it and quits without explanation.

At a glance
Default halt behaviorOnly on unhandled errorlevel
Continue command|| rem or || cd .
Check without haltingif %errorlevel% neq 0
Delayed expansionsetlocal enabledelayedexpansion
Isolate errorscmd /c command or call :label

The short version

  • A batch file stops after an error only when a command sets errorlevel to non-zero and the next command depends on it
  • Use || rem or || cd . after a command to reset errorlevel and continue execution
  • Check if %errorlevel% neq 0 to branch instead of halting, giving you control over what runs next
  • setlocal enabledelayedexpansion and delayed expansion !errorlevel! let you read the correct error state inside loops
  • Wrap risky commands in cmd /c or call to isolate their errors from the main script

Why batch files stop at errors and 'rem' lines

Say you run a batch file that copies files, then logs the result. The copy fails because the source is missing, but the script continues and writes a success message anyway. You check the log, assume it worked, and find hours later that nothing copied. That's the confusion: batch files don't halt by default, they keep running with the error buried in %errorlevel%. The real problem is when a later command does depend on errorlevel and the script suddenly quits without explanation.

A batch file halts when errorlevel is non-zero and the next command or conditional checks it. Commands like if, &&, ||, and some built-ins read errorlevel silently. If the previous command set it to 1 or higher, the script may skip a block or exit. The halt isn't the error itself: it's the uncaught state colliding with the next line.

The 'rem' line mystery comes from delayed expansion and parsing order. Inside a for loop or if block, variables including %errorlevel% are expanded once at parse time, before the loop runs. If a command inside the loop sets errorlevel, the next rem or ordinary line sees the old value unless you use !errorlevel! with delayed expansion enabled. When errorlevel stays at 1 from a previous command and the script hits a line that tests it, execution stops. The rem line isn't the cause, it's where the stale errorlevel finally gets checked.

Another trap: calling a subroutine with call :label resets errorlevel to 0 if the label exists. If you check errorlevel after the call, you're reading the call's success, not the command inside the subroutine. Use exit /b %errorlevel% at the end of the subroutine to pass the error up, or capture it in a variable before the call returns. For the detail, see our notes on shared hosting ftp deployment fails after upload.

  • Errorlevel non-zero: command failed, but the script continues unless something checks the value
  • Stale errorlevel in loops: %errorlevel% expands once; enable delayed expansion and use !errorlevel! instead
  • call :label resets errorlevel: return the error explicitly with exit /b %errorlevel%
  • Phantom halt at 'rem': the rem line itself is harmless; a previous errorlevel is triggering a hidden conditional

How to keep a batch file running after an error occurs

Command Prompt displaying batch script with errorlevel output
Command Prompt displaying batch script with errorlevel output

The simplest way to continue is to reset errorlevel after each command that might fail. Append || rem or || cd . to the line. The || operator runs the second command only if the first fails, and both rem and cd . always succeed with errorlevel 0. The script moves to the next line instead of halting.

For example, copy source.txt dest.txt || rem attempts the copy. If it fails, rem does nothing and sets errorlevel back to 0. The next command runs as if nothing went wrong. Use || cd. if you want a command that actually executes: it changes to the current directory, which always works and clears the error state.

When you need to log or handle the error instead of ignoring it, check %errorlevel% with an if statement and branch. After the failing command, write if %errorlevel% neq 0 echo Error detected and continue. The if consumes the errorlevel without halting the script. You decide what happens: log it, skip a step, or set a flag. It helps to understand steps to fix driver issues before going further.

Inside loops, enable delayed expansion at the top of the file with setlocal enabledelayedexpansion. Then use !errorlevel! instead of %errorlevel% inside the loop body. This reads the live value after each command, not the stale parse-time snapshot. Without it, every iteration sees the same old errorlevel and your checks are meaningless.

  1. Add setlocal enabledelayedexpansion at the start of the batch file, before any loops.
  2. After each command that might fail, append || rem to reset errorlevel to 0 and continue.
  3. If you need to handle the error, write if !errorlevel! neq 0 (your handling code here) immediately after the command.
  4. Use !errorlevel! with exclamation marks inside loops or if blocks; use %errorlevel% outside them.
  5. Test the script by forcing a failure (delete a source file or mistype a path) and confirm the next line runs.

Using exit /b to control subroutine errors

When you organize a batch file with subroutines (labels called with call:label) the calling script doesn't see the errorlevel from commands inside the subroutine unless you return it explicitly. The call itself succeeds with errorlevel 0, masking any failures that happened inside. You lose visibility and the script looks like it worked when it didn't.

At the end of each subroutine, add exit /b %errorlevel% to return the error state to the caller. This passes the last command's errorlevel up the chain. If the subroutine ran five commands and the third failed, exit /b returns that failure code. The caller can then check %errorlevel% and branch or halt. The other half of this decision is windows 10 folder cleanup guide.

If you want the subroutine to succeed even when an internal command fails, reset errorlevel before the return: run cd . >nul 2>&1 or rem as the last line, then exit /b 0. The subroutine always returns 0 and the calling script continues. Use this when the subroutine's job is to try something non-critical and you don't care if it fails.

For a subroutine that must halt the entire script on error, check errorlevel inside the subroutine and call exit /b 1 if something went wrong. The caller sees the 1, logs it, and decides whether to quit. You can also set a global variable like set ERROR_OCCURRED=1 inside the subroutine, then check it in the main script after the call returns.

  • exit /b %errorlevel%: return the last command's error code to the caller
  • exit /b 0: subroutine always succeeds, ignoring internal errors
  • exit /b 1: subroutine signals failure explicitly, regardless of which command failed
  • Check the returned errorlevel immediately: call :label then if %errorlevel% neq 0 goto :error

Isolating errors with cmd /c and call

Notepad showing batch file code with || rem appended to commands
Notepad showing batch file code with || rem appended to commands

Some commands set errorlevel in ways that leak into the rest of your script. A failed findstr, a missing registry key with reg query, or a network timeout can leave errorlevel at 1 or higher, and every subsequent line sees it until something resets the value. If you want a command's error contained (checked once, then discarded) run it in a subshell. If that sounds like your situation, read up on how to stop windows waking from sleep in bag next.

Wrap the command in cmd /c: for example, cmd /c findstr pattern file.txt. The cmd /c launches a new command interpreter, runs findstr, captures its errorlevel, then exits. The subshell's errorlevel returns to your script, but nothing else leaks. The environment, variables, and working directory stay unchanged. You can then check %errorlevel% and reset it with || rem before moving on.

Using call with an inline command also isolates errors, though it's less common. Write call findstr pattern file.txt and the errorlevel is local to that call. The difference: call is for subroutines and labels, while cmd /c is for any command you want fenced off. Both work; cmd /c is clearer when you're explicitly isolating a risky external command.

When multiple commands must all succeed or the whole block should be skipped, wrap them in a subroutine and check the final errorlevel. Each command inside can reset its own errorlevel with || rem, and you return a single success or failure code at the end. The calling script sees one result and branches once, instead of checking five times. People in this spot often ask about registry edit not working after saving as well.

Error isolation methods and when to use each
MethodUse whenErrorlevel behavior
|| remSingle command may fail, continue regardlessResets to 0 immediately
if %errorlevel% neq 0Need to log or branch on errorChecked but not reset; handle it yourself
cmd /c commandCommand should not affect environmentReturned to caller, rest is isolated
call :label then exit /bGroup of commands, return single resultFinal errorlevel returned by exit /b

Delayed expansion and why 'rem' lines can trigger a halt

Picture a for loop that copies files and checks errorlevel after each copy. You write %errorlevel% on every iteration, expecting to catch failures. Instead, the loop shows the same number ten times: the errorlevel from before the loop started. The script then hits a rem comment line and quits without explanation. This is parse-time expansion: the entire loop is read and all %variables% are replaced with their current values before the first iteration runs.

When a command inside the loop sets errorlevel to 1, the script's internal state changes but %errorlevel% stays frozen at the old value. A rem line does nothing itself, but if the batch interpreter checks errorlevel between lines and finds it still 1, it halts. The fix: add setlocal enabledelayedexpansion at the top, then use !errorlevel! with exclamation marks. Delayed expansion re-reads the variable every time, giving you the live value.

This also applies inside if blocks. The entire if ( ... ) multi-line body is parsed once, so %errorlevel% inside the block is the value from when the if started. If you change errorlevel inside the block and check it again, you're reading stale data. Switch to !errorlevel! and the problem disappears.

Not all commands need delayed expansion. A simple sequence of lines outside loops and if blocks works fine with %errorlevel%, because each line is parsed and executed separately. Use delayed expansion when you see repeated or wrong errorlevel readings, or when the script mysteriously halts at a rem or blank line inside a loop.

  • Enable at the top: setlocal enabledelayedexpansion, once per script
  • Inside loops: use !errorlevel! instead of %errorlevel%
  • Inside multi-line if blocks: same rule, exclamation marks give the current value
  • Outside loops: %errorlevel% works normally; delayed expansion is optional

Logging errors without halting the script

Batch script in editor showing call statement and exit /b command
Batch script in editor showing call statement and exit /b command

A batch file that silently continues after errors is worse than one that halts: you think it worked, but half the steps failed. The fix is to log every error without stopping execution. After each critical command, check errorlevel and append a message to a log file if it's non-zero, then reset errorlevel and continue.

Write command || (echo %date% %time% ERROR: command failed >> errors.log & cd .). The || runs the parenthesized block only if command fails. Inside the block, echo appends the timestamp and a message to errors.log, and cd . resets errorlevel to 0 so the script moves on. The & chains both actions inside the error block. You get a log entry and uninterrupted execution.

For commands that return useful error codes (xcopy uses 1 for no files found, 4 for insufficient memory) capture the specific value and log it. Write xcopy source dest /y then if!errorlevel! Equ 1 echo No files to copy >> errors.log. This tells you exactly what went wrong without wasting time on generic "error occurred" messages.

At the end of the script, check if the log file exists and has content: if exist errors.log echo Review errors.log for details. You can also set a variable like set ERRORS=0 at the start, increment it with set /a ERRORS+=1 in each error block, and display the total at the end. The script always finishes, but you know it had problems and where to look.

  1. Add set ERRORS=0 at the top of the script to initialize the error counter.
  2. After each critical command, write if !errorlevel! neq 0 (echo %date% %time% ERROR: [description] >> errors.log & set /a ERRORS+=1).
  3. Append || cd . to the end of the command line, or inside the error block, to reset errorlevel and continue.
  4. At the end of the script, add if %ERRORS% gtr 0 echo %ERRORS% error(s) occurred. Check errors.log.
  5. Review errors.log after each run; delete it at the start of the script with if exist errors.log del errors.log to avoid stale messages.

Questions people still ask

Does errorlevel stay set until the next command, or does it clear automatically?

Errorlevel persists until a command explicitly changes it. A successful command sets it to 0, a failed one sets it to 1 or higher, and rem or blank lines leave it unchanged. If you run five commands and only the second fails, errorlevel stays at the second command's value until something else overwrites it. Always check errorlevel immediately after the command that matters, or reset it with || rem when you want to continue.

Can I make a batch file stop on the first error instead of continuing?

Yes. Remove all || rem resets and avoid checking errorlevel with if. Instead, add @echo off and setlocal at the top, then if errorlevel 1 exit /b after each critical command. The script halts the moment any command returns non-zero. For cleaner output, redirect errors: command >nul 2>&1 || exit /b. This is the opposite of the continue-on-error pattern, useful when any failure means the rest of the script is pointless.

Why does my script halt at a blank line or 'rem' after a failed command?

The blank line or rem isn't the cause: it's where the script finally checks errorlevel and finds it non-zero from an earlier failure. This happens most often inside for loops or if blocks when you use %errorlevel% instead of !errorlevel!. Enable delayed expansion with setlocal enabledelayedexpansion and switch to exclamation marks. The script will read the current errorlevel each time instead of the stale parse-time value, and the phantom halt disappears.

What errorlevel number does a successful command return?

0. Any command that completes without errors sets errorlevel to 0. Failed commands return 1 or higher, with the specific number sometimes indicating the type of failure: xcopy uses 4 for write errors, 5 for access denied. Most commands just return 1 for any failure. Check your command's documentation if you need the exact codes, but for simple continue-or-halt logic, treat anything above 0 as failure.

Can I use && to chain commands and skip the rest if one fails?

Yes, but it's the opposite of continue-on-error. Write command1 && command2 && command3 and the chain stops at the first failure. If command1 returns errorlevel 1, command2 never runs. Use && when the second command only makes sense if the first succeeded: copy then delete the source, create a folder then move files into it. For continue-on-error, use || instead: command1 || rem runs rem only if command1 fails, resetting errorlevel to 0 so the script moves on.

I've debugged batch files that halted at blank lines for no apparent reason, and every time the cause was a stale errorlevel from earlier in a loop. Delayed expansion fixed it instantly.