How can I run a command-line application in the Windows command prompt and have the output both displayed and redirected to a file at the same time?

If, for example, I were to run the command dir > test.txt, this would redirect output to a file called test.txt without displaying the results.

How could I write a command to display the output and redirect output to a file in the Windows command prompt, similar to the tee command on Unix?

share|improve this question
13  
And please stop calling it MSDOS! The similarities between cmd.exe and that braindead command.com are minuscule, and getting smaller. – paxdiablo Apr 28 '09 at 7:06
feedback

16 Answers

There's a Win32 port of the Unix tee command, that does exactly that. See http://unxutils.sourceforge.net/ or http://getgnuwin32.sourceforge.net/

share|improve this answer
10  
The link points to a Windows implementation of the Unix command tee, so it does work on Windows. – Brian Rasmussen Apr 28 '09 at 6:50
1  
Yeah, voting up the answer and the comment. I'd actually prefer CygWin since it has everything but some people prefer non-DLL tools that they can pick and choose. – paxdiablo Apr 28 '09 at 7:10
2  
Lots of Unix utilities are also ported by GnuWin32 project, see gnuwin32.sourceforge.net. – VladV Jul 17 '09 at 7:16
1  
UnxUtils was last updated in 2003; GnuWin32 is a bit more up-to-date. – quack quixote Feb 17 '10 at 11:26
Despite being quite slow, CygWin's tee works like a charm. – Isaac Clarke Nov 19 '10 at 9:40
show 2 more comments
feedback

I was able to find a solution/workaround of redirecting output to a file and then to the console:

dir > a.txt | type a.txt

where dir is the command which output needs to be redirected, a.txt a file where to store output.

share|improve this answer
10  
This satisfies the answer, but outputs the data after the dir command has completed rather than as the data is produced. – Leigh Riffel Aug 17 '09 at 21:23
feedback

Unfortunately there is no such thing.

MS-DOS applications (and Windows console applications, too) only have a single output handle. (Well, there are two STDOUT, STDERR but it doesn't matter here) The > redirects the output normally written to the console handle to a file handle.

If you want to have some kind of multiplexing you have to use an external application which you can divert the output to. This application then can write to a file and to the console again.

share|improve this answer
feedback

A simple C# console application would do the trick:

using System;
using System.Collections.Generic;
using System.IO;

namespace CopyToFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            var buffer = new char[100];
            var outputs = new List<TextWriter>();

            foreach (var file in args)
                outputs.Add(new StreamWriter(file));

            outputs.Add(Console.Out);

            int bytesRead;
            do
            {
                bytesRead = Console.In.ReadBlock(buffer, 0, buffer.Length);
                outputs.ForEach(o => o.Write(buffer, 0, bytesRead));
            } while (bytesRead == buffer.Length);

            outputs.ForEach(o => o.Close());
        }
    }
}

To use this you just pipe the source command into the program and provide the path of any files you want to duplicate the output to. For example:

dir | CopyToFiles files1.txt files2.txt

Will display the results of dir as well as store the results in both files1.txt and files2.txt.

Note that there isn't much (anything!) in the way of error handling above, and supporting multiple files may not actually be required.

share|improve this answer
Hmm, download tee/cygwin for nothing or buy MSVS with my hard-earned cash for a piddly little program like that? That's a tough one :-) – paxdiablo Apr 28 '09 at 7:08
5  
You don't need visual studio to compile that, the commandline tools are actually free. just google ".net sdk download" for the link (the direct link seems to change around but google always seems to work). – Kris Apr 28 '09 at 7:17
2  
Visual Studio Express is free as well, but I would still just use tee for this. – Brian Rasmussen Apr 28 '09 at 7:39
Home-made tee implementation? And have to learn C#? Use tee.. really. – Jay Sep 8 '09 at 17:02
1  
cygwin is a pain to install. Upvote to you because this is what I was looking for. – Samaursa Jul 24 '11 at 16:06
show 1 more comment
feedback

I agree with Brian Rasmussen, the unxutils port is the easiest way to do this. In the Batch Files section of his Scripting Pages Rob van der Woude provides a wealth of information on the use MS-DOS and CMD commands. I thought he might have a native solution to your problem and after digging around there I found TEE.BAT, which appears to be just that, an MS-DOS batch language implementation of tee. It is a pretty complex-looking batch file and my inclination would still be to use the unxutils port.

share|improve this answer
That tee.bat thing looks nice. Hope OP checks this out. – Jay Sep 8 '09 at 17:06
5  
Note that using TEE.BAT will output after the command has completed, just like the "dir > a.txt | type a.txt" example posted nearby. – adzm Aug 5 '10 at 13:19
feedback

tori3852

I found that

dir > a.txt | type a.txt

didn't work (first few lines of dir listing only - suspect some sort of process forking and the second part, the 'type' command terminated before the dire listing had completed? ), so instead I used:-

dir > z.txt && type z.txt

which did - sequential commands, one completes before the second starts. Thanks. Good to find this stuff, appreciated.

share|improve this answer
feedback

mtee is a small utility which works very well for this purpose. It's free, source is open, and it Just Works.

You can find it at http://www.commandline.co.uk.

Used in a batch file to display output AND create a log file simultaneously, the syntax looks like this:

    someprocess | mtee /+ mylogfile.txt

Where /+ means to append output.

This assumes that you have copied mtee into a folder which is in the PATH, of course.

share|improve this answer
feedback

Here's a sample of what I've used based on one of the other answers

@echo off
REM SOME CODE
set __ERROR_LOG=c:\errors.txt
REM set __IPADDRESS=x.x.x.x

REM Test a variable
if not defined __IPADDRESS (
     REM Call function with some data and terminate
     call :TEE %DATE%,%TIME%,IP ADDRESS IS NOT DEFINED
     goto :EOF
)

REM If test happens to be successful, TEE out a message and end script.
call :TEE Script Ended Successful
goto :EOF


REM THE TEE FUNCTION
:TEE
for /f "tokens=*" %%Z in ("%*") do (
     >  CON ECHO.%%Z
     >> "%__ERROR_LOG%" ECHO.%%Z
     goto :EOF
)
share|improve this answer
feedback
@echo on

set startDate=%date%
set startTime=%time%

set /a sth=%startTime:~0,2%
set /a stm=1%startTime:~3,2% - 100
set /a sts=1%startTime:~6,2% - 100


fullprocess.bat > C:\LOGS\%startDate%_%sth%.%stm%.%sts%.LOG | fullprocess.bat

This will create a log file with the current datetime and you can the console lines during the process

share|improve this answer
4  
aren't you calling the same program twice with this? – elcool Apr 29 at 4:40
feedback

Following helps if you want something really seen on the screen - even if the batch file was redirected to a file. The device CON maybe used also if redirected to a file

Example:

ECHO first line on normal stdout. maybe redirected
ECHO second line on normal stdout again. maybe redirected
ECHO third line is to ask the user. not redirected  >CON
ECHO fourth line on normal stdout again. maybe redirected

Also see good redirection description: http://www.p-dd.com/chapter7-page14.html

share|improve this answer
feedback

How do I display and redirect output to a file. Suppose if I use dos command, dir > test.txt ,this command will redirect output to file test.txt without displaying the results. how to write a command to display the output and redirect output to a file using DOS i.e., windows command prompt, not in UNIX/LINUX.

You may find these commands in biterscripting ( http://www.biterscripting.com ) useful.

var str output
lf > $output
echo $output                            # Will show output on screen.
echo $output > "test.txt"               # Will write output to file test.txt.
system start "test.txt"                 # Will open file test.txt for viewing/editing.
share|improve this answer
feedback

This works, though it's a bit ugly:

dir >_ && type _ && type _ > a.txt

It's a little more flexible than some of the other solutions, in that it works statement-by-statement so you can use it to append as well. I use this quite a bit in batch files to log and display messages:

ECHO Print line to screen and log to file.  >_ && type _ && type _ >> logfile.txt

Yes, you could just repeat the ECHO statement (once for the screen and the second time redirecting to the logfile), but that looks just as bad and is a bit of a maintenance issue. At least this way you don't have to make changes to messages in two places.

Note that _ is just a short filename, so you'll need to make sure to delete it at the end of your batch file (if you're using a batch file).

share|improve this answer
That's only useful if you want to display the contents AFTER your process has run. And that isn't a hard problem to solve. – Christopher Painter Mar 25 '11 at 19:01
Yeah, I guess this addresses a slightly different problem from what the original poster was asking. – MTS Apr 27 '11 at 22:43
feedback

dir 1>a.txt 2>&1 | type a.txt

This will help to redirect both STDOUT and STDERR

share|improve this answer
This doesn't work. I tried using this to launch the JBoss run.bat and it chokes during startup and the server freezes. There are problems with this method... – djangofan Sep 21 at 0:05
feedback

Check this out: wintee

No need for cygwin.

I did encounter and report some issues though.

share|improve this answer
Why the down vote? 95% of replies here have one thing in common: the output is redirected only after the initial command has finished: read the comments. UNIX utility tee outputs real time. wtee has the same functionality. If you don’t mind the bugs, it will do just fine. – davor Sep 27 at 16:49
+1 for wintee. Simple and works like a charm. – Jake Stoeffler Sep 27 at 17:10
feedback

This works in real time but is also kind a ugly and the performance is slow. Not well tested either:

@echo off
cls
SET MYCOMMAND=dir /B
ECHO File called 'test.bat' > out.txt
for /f "usebackq delims=" %%I in (`%MYCOMMAND%`) do (
  ECHO %%I
  ECHO %%I >> out.txt
) 
pause
share|improve this answer
No, it's not real time, it waits until %MYCOMMAND% is finished and it fails in many cases. It skips empty lines, lines beginning with ; fails with content like <space>/<TAB>, ON, OFF or /?. But the rest could sometimes work :-) – jeb Sep 20 at 18:09
yeah, your right. well, maybe this and other answers in this thread will give someone else the inspiration to come up with something new that actually works... – djangofan Sep 20 at 23:56
feedback

An alternative is to tee stdout to stderr within your program:

in java:

System.setOut(new PrintStream(new TeeOutputStream(System.out, System.err)));

Then, in your dos batchfile: java program > log.txt

The stdout will go to the logfile and the stderr (same data) will show on the console.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.