首页 > 代码库 > 关于Window的Dos Batch 文件编写的常识

关于Window的Dos Batch 文件编写的常识

Redirect "all" output to a single file:

Run:

test.bat > test.txt 2>&1

and you‘ll get this text on screen (we‘ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

You should also get a file named test.txt with the following content:

This text goes to Standard Output
This text goes to Standard Error

Note: The commands
                test.bat  > test.txt 2>&1
                test.bat 1> test.txt 2>&1
            test.bat 2> test.txt 1>&2
all give identical results.


Redirect errors to a separate error log file:

Run:

test.bat > testlog.txt 2> testerrors.txt

and you‘ll get this text on screen (we‘ll never get rid of this line on screen, as it is sent to the Console and cannot be redirected):

This text goes to the Console

You should also get a file named testlog.txt with the following content:

This text goes to Standard Output

and another file named testerrors.txt with the following content:

This text goes to Standard Error


Some "best practices" when using redirection in batch files:

  • Use >filename.txt 2>&1 to merge Standard Output and Standard Error and redirect them together to a single file.
    Make sure you place the redirection "commands" in this order.

  • Use >logfile.txt 2>errorlog.txt to redirect success and error messages to separate log files.

  • Use >CON to send text to the screen, no matter what, even if the batch file‘s output is redirected.
    This could be useful when prompting for input even if the batch file‘s output is being redirected to a file.

  • Use 1>&2 to send text to Standard Error.
    This can be useful for error messages.

  • It‘s ok to use spaces in redirection commands. Note however, that a space between an ECHO command and a > will be redirected too.
    DIR>filename.txt and DIR > filename.txt are identical, ECHO Hello world>filename.txt and ECHO Hello world > filename.txt are not, even though they are both valid.
    It is not ok to use spaces in >> or 2> or 2>&1 or 1>&2 (before or after is ok).

  • In Windows NT 4, early Windows 2000 versions, and OS/2 there used to be some ambiguity with ECHOed lines ending with a 1 or 2, immediately followed by a >:
    ECHO Hello world2>file.txt would result in an empty file file.txt and the text Hello world (without the trailing "2") on screen (CMD.EXE would interpret it as ECHO Hello world 2>file.txt).
    In Windows XP the result is no text on screen and file.txt containing the line Hello world2, including the trailing "2" (CMD.EXE interprets it asECHO Hello world2 >file.txt).
    To prevent this ambiguity, either use parentheses or insert an extra space yourself:
    ECHO Hello World2 >file.txt
    (ECHO Hello World2)>file.txt

  • "Merging" Standard Output and Standard Error with 2>&1 can also be used to pipe a command‘s output to another command‘s Standard Input:
    somecommand 2>&1 | someothercommand