3

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
Julez
  • 65
  • 2
  • 8
  • 6
    a better command for resetting the errorlevel is `ver >nul` (`dir` a folder with many files may need some time, `ver` is faster). Another (quite hackish and intransparent method) is `(call)`. [In case, you look for a language independent method to get the date](https://stackoverflow.com/a/18024049/2152082) – Stephan Jun 02 '17 at 07:14
  • 4
    @Stephan, it's `(call )` to reset the `ErrorLevel`; `(call)` set it to `1`... – aschipfl Jun 02 '17 at 08:55

1 Answers1

2

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953