Julez
Julez

Reputation: 65

CMD What is this command good for: dir >NUL

I'm analyzing a code of a former worker that does not work here anymore and he used alot this command:

dir >NUL

I know that this redirects the output to a "Nul device" and that CMD.EXE interprets it as dir 1>Nul but I do not see the purpose of it. He wrote as comment: Reset errorlevel.

Example:

for /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set _Year=%%c&set _Month=%%a&set _Day=%%b)
set _Day=%_Day: =%
set _TODAY_FORMATTED=%_Year%%_Month%%_Day%
:: Self Check
::   Reset errorlevel
dir >NUL
set /a _TEST=%_TODAY_FORMATTED%-1
set _rc=%errorlevel%
:: Reset errorlevel
dir >NUL
if %_rc% NEQ 0 call :SELFCHECKERROR& goto end

Upvotes: 3

Views: 10784

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

It does exactly what the comments say it does :-)

C:\pax> dir x:
The device is not ready.

C:\pax> echo %errorlevel%
1

C:\pax> dir >nul:

C:\pax> echo %errorlevel%
0

The error level is used to communicate errors from executables (though not every executable sets an error level, unfortunately) back to the command shell.

Executing a program which is known to succeed is a safe way to reset it (a) though dir is not really a good option since it may take some time to walk through all the files in the current directory. A command like ver >nul: is probably better.


(a) Do not think that you can simply do set errorlevel=0, the error level is a "special" variable that reports the state of the system - if you set it, that creates a real variable which will then refuse to report the actual error level from future commands.

Upvotes: 2

Related Questions