Search code examples
windowshttp-redirectbatch-fileerrorlevel

Redirecting command-line output to keep error messages from showing in the command window


I'm testing the existence of a folder, and, depending on its existence, I want to run different commands:

DIR %MYDIR%\tmp > test.txt
IF ERRORLEVEL 1 (
      echo/FOLDER DOES NOT EXIST
) else (
      echo/FOLDER EXISTS
      )

The problem is that if the folder doesn't exist I'm getting this error in addition to the standard output:

The system cannot find the file specified.

I'd like to display the correct output without getting the error.


Solution

  • How about this:

    DIR %MYDIR%\tmp > nul 2>&1
    

    "> nul" means to redirect standard output to the file nul (the bit bucket).

    "2>" is used to redirect standard error (descriptor 2). So "2>&1" is used to redirect standard error to means that standard output (descriptor 1 -- so "> null and 1> null are be the same). Alternatively you could use "2> nul".