Batch How To ...

Display & Redirect Output

http://www.robvanderwoude.com/battech_redirection.php

On this page I'll try to explain how redirection works.
To illustrate my story there are some examples you can try for yourself.

For an overview of redirection and piping, view my original redirection page.

Display text

To display a text on screen we have the ECHO command:

ECHO Hello world

This will show the following text on screen:

Hello world

When I say "on screen", I'm actually referring to the
"DOS Prompt", "console" or "command window", or
whatever other "alias" is used.

Streams

The output we see in this window may all look alike, but it can
actually be the result of 3 different "streams" of text, 3
"processes" that each sends their text to the same window.

Those of you familiar with one of the Unix/Linux shells probably
know what these streams are:

  • Standard Output
  • Standard Error
  • Console

Standard Output is the stream where all, well, standard output of
commands is being sent to.
The ECHO command
sends all its output to Standard Output.

Standard Error is the stream where many (but not all)
commands send their error messages.

And some, not many, commands send their output to the screen
bypassing Standard Output and Standard Error, they use the Console. By
definition Console isn't a stream.

There is another stream, Standard Input: many commands
accept input at their Standard Input instead of directly from the keyboard.
Probably the most familiar example is MORE:

DIR /S | MORE

where the MORE command
accepts DIR's
Standard Output at its own Standar Input, chops the stream in blocks of 25
lines (or whatever screen size you may use) and sends it to its own Standard
Output.

(Since MORE's
Standard Input is used by DIR, MORE must catch its keyboard presses (the "Any Key")
directly from the keyboard buffer instead of from Standard Input.)

Redirection

You may be familiar with "redirection to NUL" to hide
command output:

ECHO Hello world>NUL

will show nothing on screen.
That's because >NUL redirects all
Standard Output to the NUL device, which does nothing but discard it.

Now try this (note the typo):

EHCO Hello world>NUL

The result may differ for different operating system versions, but
in Windows XP I get the following error message:

'EHCO' is not recognized as an internal or external command,
operable program or batch file.

This is a fine demonstration of only Standard
Output being redirected to the NUL device, but Standard Error still being
displayed.

Redirecting Standard Error in "true" MS-DOS (COMMAND.COM)
isn't possible (actually it is, by using the CTTY command, but that would redirect all output
including Console, and input, including keyboard).
In Windows NT 4 and later (CMD.EXE) and in OS/2 (also CMD.EXE) Standard
Error can be redirected by using 2> instead
of>

A short demonstration. Try this command:

ECHO Hello world 2>NUL

What you should get is:

Hello world

You see? The same result you got with ECHO Hello world without the
redirection.
That's because we redirected the Standard Error stream to the NUL device, but
the ECHO command sent its output to the Standard Output stream, which was not redirected.

Now make a typo again:

EHCO Hello world 2>NUL

What did you get? Nothing
That's because the error message was sent to the Standard Error stream, which
was in turn redirected to the NUL device by 2>NUL

When we use > to
redirect Standard Output, CMD.EXE interprets this as 1>, as can be seen by writing and running this one-line batch file
"test.bat":

DIR > NUL

Now run test.bat in CMD.EXE and watch the result:

C:\>test.bat

C:\>DIR  1>NUL

C:\>_

It looks like CMD.EXE uses 1 for Standard Output and 2 for Standard
Error. We'll see how we can use this later.

Ok, now that we get the idea of this concept of
"streams", let's play with it.
Copy the following code into Notepad and save it as "test.bat":

@ECHO OFF

ECHO This text goes to Standard Output

ECHO This text goes to Standard Error 1>&2

ECHO This text goes to the Console>CON

Run test.bat in CMD.EXE, and this is what you'll get:

C:\>test.bat

This text goes to Standard Output

This text goes to Standard Error

This text goes to the Console

C:\>_

Now let's see if we can separate the streams again.
Run:

test.bat > NUL

and you should see:

C:\>test.bat

This text goes to Standard Error

This text goes to the Console

C:\>_

We redirected Standard Output to the NUL device, and what was left
were Standard Error and Console.

Next, run:

test.bat 2> NUL

and you should see:

C:\>test.bat

This text goes to Standard Output

This text goes to the Console

C:\>_

We redirected Standard Error to the NUL device, and what was left
were Standard Output and Console.

Nothing new so far. But the next one is new:

test.bat > NUL 2>&1

and you should see:

C:\>test.bat

This text goes to the Console

C:\>_

This time we redirected both Standard Output and Standard
Error to the NUL device, and what was left was only Console.
It is said Console cannot be redirected, and I believe that's true. I can
assure you I did try!

To get rid of screen output
sent directly to the Console, either run the program in a separate window
(using the START command),
or clear the screen immediately afterwards (CLS).

In this case, we could also have used test.bat >NUL 2>NUL
This redirects Standard Output to the NUL device and Standard Error to the
same
 NUL device.
With the NUL device that's no problem, but when redirecting to a file one
of the redirections will lock the file for the other
redirection.
What 2>&1 does,
is merge Standard Error into the Standard Output stream, so
Standard output and Standard Error will continue as a single stream.

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

Notes: The commands

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

Nothing is impossible, not even redirecting the Console output.

Unfortunately, it can be done only in the old MS-DOS versions that
came with a CTTY command.

The general idea was this:

CTTY NUL

ECHO Echo whatever you want, it won't be displayed on screen no
matter what.

ECHO By the way, did I warn you that the keyboard doesn't work
either?

ECHO I suppose that's why CTTY is no longer available on Windows
systems.

ECHO The only way to get control over the computer again is a
cold reboot,

ECHO or the following command:

CTTY CON

A pause or prompt for input before the CTTY CON command meant one had to press the reset
button!

Besides being used for redirection to the NUL device, with CTTY COM1 the control could be passed on to a
terminal on serial port COM1.

Escaping Redirection (not to be interpreted as
"Avoiding Redirection")

Redirection always uses the main or first command's
streams:

START command > logfile

will redirect START's
Standard Output to logfile, not command's!
The result will be an empty logfile.

A workaround that may look a bit intimidating is grouping the
command line and escaping the redirection:

START CMD.EXE /C ^(command ^> logfile^)

What this does is turn the part between parentheses into a
"literal" (uninterpreted) string that is passed to the command
interpreter of the newly started process, which then in turn does interpret
it.
So the interpretation of the parenthesis and redirection is delayed, or
deferred.

Note:

Be careful when using workarounds like these, they may be broken
in future (or even past) Windows versions.

A safer way to redirect STARTed
commands' output would be to create and run a "wrapper" batch file
that handles the redirection.
The batch file would look like this:

command > logfile

and the command line would be:

START batchfile

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 as ECHO 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

Batch: Display & Redirect Output的更多相关文章

  1. python display color output

    起因 在开发项目过程中,为了方便调试代码,经常会向stdout中输出一些日志,默认的这些日志就直接显示在了终端中.而一般的应用服务器,第三方库,甚至服务器的一些通告也会在终端中显示,这样就搅乱了我们想 ...

  2. Batch - Windows Batch 常用命令

    比较符号(不能用 < , >) The reason operators like > are not used is because they have special meani ...

  3. BOOST Converter Analog/Digital Adjusted Output Voltage TPS61045 MAX1932

    DIGITALLY ADJUSTABLE BOOST CONVERTER The TPS61045 is a high frequency boost converter with digitally ...

  4. 手把手教你编写一个具有基本功能的shell(已开源)

    刚接触Linux时,对shell总有种神秘感:在对shell的工作原理有所了解之后,便尝试着动手写一个shell.下面是一个从最简单的情况开始,一步步完成一个模拟的shell(我命名之为wshell) ...

  5. Unity3D Optimizing Graphics Performance for iOS

    原地址:http://blog.sina.com.cn/s/blog_72b936d801013ptr.html icense Comparisons http://unity3d.com/unity ...

  6. Cisco IOS debug command reference Command A through D

    debug aaa accounting through debug auto-config debug aaa accounting : to display information on acco ...

  7. (英文版)使用Visual Studio 2015 编写 MASM 汇编程序!

    原文地址:http://kipirvine.com/asm/gettingStartedVS2015/index.htm#CreatingProject Getting Started with MA ...

  8. linux tee 命令详解

    man tee: NAME tee - read from standard input and write to standard output and files SYNOPSIS tee [OP ...

  9. shell 脚本阅读之二——ltp工具下的runltp

    #!/bin/sh ################################################################################ ## ## ## ...

随机推荐

  1. SQL 正则表达式使模式匹配和数据提取变得更容易

    SQL Server 2005 正则表达式使模式匹配和数据提取变得更容易 David Banister 本文讨论: 使用正则表达式进行高效的 SQL 查询 SQL Server 2005 对正则表达式 ...

  2. eclipse代码左虚线对齐设置

    前言 : 前阵子看到同事的eclipse左边有虚线对齐.有点好奇~刚开始以为是装了神马插件, 于是百度了下, 貌似没有找着. 一怒之下,逗比了半个小时,终于探索出来了~~ 设置如下 : 点击confi ...

  3. eclispe搭建android平台

    1.不推荐在线安装android ADT,因为需要FQ.可以在网上下载ADT,然后离线安装. 离线安装方式:help->Install ->点击add然后选择你的安装包(不需要解压),一直 ...

  4. Java split用法

    Java split用法 java.lang.string.split split 方法  将一个字符串分割为子字符串,然后将结果作为字符串数组返回. stringObj.split([separat ...

  5. linux下配置squid http proxy过程

      国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html内部邀请码:C8E245J (不写邀请码,没有现金送)国 ...

  6. iOS开发——新特性Swift篇&Swift 2.0 异常处理

    Swift 2.0 异常处理 WWDC 2015 宣布了新的 Swift 2.0. 这次重大更新给 Swift 提供了新的异常处理方法.这篇文章会主要围绕这个方面进行讨论. 如何建造异常类型? 在 i ...

  7. JAVA实现的异步redisclient

    再使用redis的过程中,发现使用缓存尽管好,可是有些地方还是比較难权衡,缓存对象大了,存储对象时的序列化工作非常繁重,消耗大量cpu:那么切分成非常小的部分吧,存取的次数变多了,redisclien ...

  8. c++中静态成员变量 静态成员函数 全局变量与静态函数的关系 字符串中括号的匹配编程 (笔试经历)

    笔试经历 1 类中的静态变量不能通过构造函数参数列表来初始化,因为静态变量不属于哪个对象.同时静态变量在不初始化的情况下系统会自动为变量赋值,数值型赋值为零,字符型赋值为空. 非静态变量只有在定义时才 ...

  9. TextView设置动态改变颜色

    通过TextView的setTextColor方法进行文本颜色的设置, 这里可以有3种方式进行设置: 第1种:tv.setTextColor(android.graphics.Color.RED);/ ...

  10. typeid关键字

    这么看下去太要命了,有太多东西要学了... 而且视频看起来的确费神,费脑,费耳朵. 所以决定由视频驱动转向代码驱动.主攻vs,c++然后先把界面东西做出来,然后在想后面的东西. 所以今天 [先上来看了 ...