Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

File redirection in Windows and %errorlevel%

Tags:

Lets say we want to create an empty file in windows with the following command:

type nul > C:\does\not\exist\file.txt 

the directory does not exist, so we get the error:

The system cannot find the path specified 

If you print out the %errorlevel% the output is:

echo %errorlevel% 0 

Yet the command was not successful!

I noticed, that windows does not set the %errorlevel% of the last command if you use redirection..

Is there a way around this?

like image 396
lukuluku Avatar asked Apr 27 '12 16:04

lukuluku


People also ask

What is Errorlevel in batch file?

Batch file error level: %ERRORLEVEL% is an environment variable that contains the last error level or return code in the batch file – that is, the last error code of the last command executed. Error levels may be checked by using the %ERRORLEVEL% variable as follows: IF %ERRORLEVEL% NEQ 0 ( DO_Something )

What is Errorlevel?

In Microsoft Windows and MS-DOS, an errorlevel is the integer number returned by a child process when it terminates. Errorlevel is 0 if the process was successful. Errorlevel is 1 or greater if the process encountered an error.

How do I redirect standard output and error to a file in Windows?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.


1 Answers

You can use the following:

C:\>type nul > C:\does\not\exist\file.txt && echo ok || echo fail The system cannot find the path specified. fail  C:\>echo %errorlevel% 1 

I always assumed the && and || operators used ERRORLEVEL, but apparently not.

Very curious that ERRORLEVEL is set after redirection error only if you use the || operator. I never would have guessed. Nor would I ever have bothered to test if not for your excellent question.

If all you want to do is set the ERRORLEVEL upon redirection failure, then of course you can simply do:

type nul > C:\does\not\exist\file.txt || rem 
like image 190
dbenham Avatar answered Oct 19 '22 11:10

dbenham