7

I need to specify my own exit code in my batch script when it successful exits on a if exist clause. As you will notice, I specified it as an exit 5, I have also tried exit /b 5 but nothing has worked. Any suggestions?

@ECHO OFF
CLS

set SOURCE_PARENT=%1
set FOLDER=%2
set TARGET_FILE=%3

net use S: %SOURCE_PARENT% 
net use T: %TARGET_FILE%

if exist T:\%FOLDER% (
  echo Folder exists, process exiting
  net use S: /Delete /y
  net use T: /Delete /y
  exit 5
) else (
  mkdir T:\%FOLDER%
)

xcopy S:\%FOLDER% T:\%FOLDER% /E /I /H

net use S: /Delete /y
net use T: /Delete /y

exit
5
  • 1
    Why do you think it did not work? did you try to check errorlevel after calling the script? Commented Jan 24, 2014 at 17:39
  • it has to exit /b 5.How do call iy?From another batch? Commented Jan 24, 2014 at 17:39
  • I have the exit code returned to my java which is calling it. In debugging, the exit code remains a 0 Commented Jan 24, 2014 at 18:06
  • 2
    Show us how you are calling it from your Java code. Commented Jan 24, 2014 at 18:16
  • Then it is more related to java, not to batch... Commented Jan 24, 2014 at 19:59

2 Answers 2

12

If you have a script script.bat containing:

@echo off
echo Hello from script.
exit /b 5

In the command prompt or from another script call

test.bat
echo %errorlevel%

It should show:

C:\Temp>script.bat

Hello from script.

C:\Temp>echo %errorlevel%

5

Sign up to request clarification or add additional context in comments.

2 Comments

This explains the difference between ERRORLEVEL (the exit code) and %ERRORLEVEL% (the environment variable): ERRORLEVEL is not %ERRORLEVEL%
I believe, you need to use CALL in the second script, such as CALL test.bat
0

Unfortunately plain exit /b N only works if you run batch file via call (as @james-john-mcguire-jahmic mentions). So this won't give expected results:

>mybatch.bat || echo Fail

The only reliably working option I found is to call a subshell:

"%ComSpec%" /c exit N

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.