Batch: If exist statement causes errorlevel to be 1 although it succeeded

2.8k Views Asked by At

In my batch file (a normal *.bat file), I want to check if a file exists. If it exists, it should be copied, if not, an output should be written to the shell. After the if statement, I want to check if the (possible) copy command executed successfully. I'm doing that with an errorlevel check.

But although the if-statement seems to work, the errorlevel after the statement is always 1. I know that the if-statement works because when the file does not exist, the respective message is written to the shell.

Here is the code:

if errorlevel 1 goto error
...     
if exist %my_path_and_file% (
copy %my_path_and_file% %my_target_path_and_file%

) ELSE (
echo File %immo_path_and_file% does not exist
)

if errorlevel 1 goto error    
...    
:error    
...

Why is the errorlevel always 1 after the if-statement, although the correct output is File xxx does not exist and the if-statement seemed to run successfully?

SOLVED: My mistake. The errorlevel was set to 1 by another statement BEFORE the IF statement. I also misplaced the first erroelevel check in my posted code above - sorry for that. There was some code between the first check and the IF statement which caused the errorlevel set to 0. I will correct it now. Thanks for all answers!

2

There are 2 best solutions below

0
On

if exist doesn't set an errorlevel, even if the file doesn't exists:

C:\Users>if exist qwerty (echo true) else echo false
false

C:\Users>echo %errorlevel%
0

C:\Users>if exist qwerty rem

C:\Users>echo %errorlevel%
0
1
On

Try with

if %errorLevel% == 1 (
    goto error
) else (
    echo ok
)