-
Windows Command Prompt and batch scripts support powerful I/O redirection capabilities.
These help you control where command output and error messages go, such as into log files, null devices, or other streams.
Before we look at syntax, understand that CMD has two main output channels:
Stream Number Purpose stdout 1 Standard Output stderr 2 Standard Error 🔧 These are usually displayed together in the console, but can be split and redirected independently.
-
Redirects stdout to a file. If the file exists, it is overwritten.
DIR > output.txt
📌 Example: Save directory listing to
output.txt -
Appends stdout to the file without deleting existing content.
ECHO Starting log... >> log.txt DIR >> log.txt
📌 Good for logging over time.
-
Redirects stderr (error messages) to a file, overwriting existing content.
DIR nonexistentfolder 2> error.txt
✅
error.txtwill contain:File Not Found -
Just like
>>, but for error stream:DIR nonexistentfolder 2>> error.log
-
Redirects
stderr (2)to the same place as stdout (1).DIR > all_output.txt 2>&1
✅
all_output.txtwill contain both normal and error messages.⚠️ Order matters:2>&1must come after>or>>.DIR 2>&1 > output.txt
This will not work as intended.
-
Use
NULto silence output:DIR > NUL :: suppress normal output DIR 2> NUL :: suppress errors DIR > NUL 2>&1 :: suppress all output
-
@ECHO OFF ECHO Starting backup... >> backup.log XCOPY C:\data D:\backup /E /I >> backup.log 2>&1 ECHO Backup completed. >> backup.log
-
PING 10.0.0.1 -n 1 -w 1000 > NUL 2>&1 IF ERRORLEVEL 1 ( ECHO Host unreachable! )
-
COPY *.* D:\dest > output.log 2> error.log
-
( ECHO Starting batch job... DIR COPY file.txt D:\backup\ ) > full_output.txt 2>&1
✅ All output and errors from the block go to
full_output.txt. -
> log.txtThis is a quick way to empty a file before appending to it.
| Syntax | Meaning |
|---|---|
> |
Redirect stdout (overwrite) |
>> |
Redirect stdout (append) |
2> |
Redirect stderr (overwrite) |
2>> |
Redirect stderr (append) |
2>&1 |
Merge stderr into stdout |
> NUL |
Discard stdout |
2> NUL |
Discard stderr |
> file 2>&1 |
All output (both streams) to file |
> NUL 2>&1 |
Suppress all output |