Содержание
- Redirecting error messages from Command Prompt: STDERR/STDOUT
- Summary
- Example
- Display & Redirect Output
- Display text
- Streams
- Redirection
- Redirect «all» output to a single file:
- Redirect errors to a separate error log file:
- Escaping Redirection (not to be interpreted as «Avoiding Redirection»)
- Console. Error Property
- Definition
- Property Value
- Examples
- Remarks
- Redirecting error messages from Command Prompt: STDERR/STDOUT
- Summary
- Example
- Redirecting error messages from Command Prompt: STDERR/STDOUT
- Summary
- Example
Redirecting error messages from Command Prompt: STDERR/STDOUT
This article describes redirecting error messages from Command Prompt.
Original product version: В Visual C++
Original KB number: В 110930
Summary
When redirecting output from an application using the > symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.
Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol. This selects the second output stream that is STDERR.
Example
The command dir file.xxx (where file.xxx does not exist) will display the following output:
Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876
File Not Found
If you redirect the output to the NUL device using dir file.xxx > nul , you will still see the error message:
To redirect the error message to NUL, use the following command:
Or, you can redirect the output to one place, and the errors to another.
You can print the errors and standard output to a single file by using the &1 command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:
Источник
Display & Redirect Output
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:
This will show the following text on screen:
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 send their text to thee 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 :
where the MORE command accepts DIR ‘s Standard Output at its own Standard 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:
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):
The result may differ for different operating system versions, but in Windows XP I get the following error message:
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:
What you should get is:
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:
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»:
Now run test.bat in CMD.EXE and watch the result:
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»:
Run test.bat in CMD.EXE, and this is what you’ll get:
Now let’s see if we can separate the streams again.
Run:
and you should see:
We redirected Standard Output to the NUL device, and what was left were Standard Error and Console.
and you should see:
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:
and you should see:
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!
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:
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):
You should also get a file named test.txt with the following content:
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:
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):
You should also get a file named testlog.txt with the following content:
and another file named testerrors.txt with the following content:
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:
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:
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:
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 START ed commands’ output would be to create and run a «wrapper» batch file that handles the redirection.
The batch file would look like this:
Источник
Console. Error Property
Definition
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Gets the standard error output stream.
Property Value
A TextWriter that represents the standard error output stream.
Examples
The following example is a command line utility named ExpandTabs that replaces tab characters in a text file with four spaces, the value defined by the tabSize variable. It redirects the standard input and output streams to files, but uses the Error property to write the standard error stream to the console. It can be launched from the command line by supplying the name of the file that contains tab characters and the name of the output file.
The following example is a simple text file viewer that displays the contents of one or more text files to the console. If there are no command line arguments, or if any files passed as command line arguments do not exist, the example calls the SetError method to redirect error information to a file, calls the OpenStandardError method in the process of reacquiring the standard error stream, and indicates that error information was written to a file.
Note that the StreamWriter.AutoFlush property is set to true before reacquiring the error stream. This ensures that output will be sent to the console immediately rather than buffered.
This standard error stream is set to the console by default. It can be set to another stream with the SetError method. After the standard error stream is redirected, it can be reacquired by calling the OpenStandardError method.
In console applications whose informational output is often redirected to a file, the standard error stream available through the Error property can be used to display information to the console even if output is redirected. The following example displays product tables for 10 numbers at a time starting with 1. After every set of 10 numbers, the Error property is used to ask the user whether to display the next set. If the standard output is redirected to a file, the user is still asked whether the routine should generate the next set of products.
Источник
Redirecting error messages from Command Prompt: STDERR/STDOUT
This article describes redirecting error messages from Command Prompt.
Original product version: В Visual C++
Original KB number: В 110930
Summary
When redirecting output from an application using the > symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.
Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol. This selects the second output stream that is STDERR.
Example
The command dir file.xxx (where file.xxx does not exist) will display the following output:
Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876
File Not Found
If you redirect the output to the NUL device using dir file.xxx > nul , you will still see the error message:
To redirect the error message to NUL, use the following command:
Or, you can redirect the output to one place, and the errors to another.
You can print the errors and standard output to a single file by using the &1 command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:
Источник
Redirecting error messages from Command Prompt: STDERR/STDOUT
This article describes redirecting error messages from Command Prompt.
Original product version: Visual C++
Original KB number: 110930
Summary
When redirecting output from an application using the > symbol, error messages still print to the screen. This is because error messages are often sent to the Standard Error stream instead of the Standard Out stream.
Output from a console (Command Prompt) application or command is often sent to two separate streams. The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol. This selects the second output stream that is STDERR.
Example
The command dir file.xxx (where file.xxx does not exist) will display the following output:
Volume in drive F is Candy Cane Volume Serial Number is 34EC-0876
File Not Found
If you redirect the output to the NUL device using dir file.xxx > nul , you will still see the error message:
To redirect the error message to NUL, use the following command:
Or, you can redirect the output to one place, and the errors to another.
You can print the errors and standard output to a single file by using the &1 command to redirect the output for STDERR to STDOUT and then sending the output from STDOUT to a file:
Источник
A while back I was working on a small Proof of concept where I needed to use console based client to connect to a server and use it to send and receive messages to other clients.As you must be aware of that all windows process are attached with a standard error ,input and output streams.Input stream by default point to keyboard and in case of a console application both standard error and output stream point to console.That means any program related output and exceptions are by default displayed in console window.That was problematic for me as couple of third party dlls and framework which I was using had extensive logging on errors and both the output and error were getting terribly mixed up.Most of these errors were not fatal errors and were not supposed to close the application e.g. whenever client and server TCP connection was lost an exception was raised and used to come in red font on console window.
Solution was to redirect error stream to something other than console and let only valid output be displayed on console.
Redirection in case of a child process
By child process I just mean one process spawning another process.It is quite simple in case you want to start a child process and want its output or errors to be redirected i.e. you have a console application (or any kind of application for that matter) and you start another process from it and redirect its error to a file.
var childProcess = new Process(); childProcess.StartInfo.FileName = "ChildProcess.exe"; childProcess.StartInfo.UseShellExecute = false; childProcess.StartInfo.RedirectStandardError = true; childProcess.Start(); using (StreamReader reader = childProcess.StandardError) { string result = reader.ReadToEnd(); //WRITE TO A FILE OR TO ANY OTHER TARGET } childProcess.WaitForExit();
You need to make sure that UseShellExecute = false as it makes sure that process is started as a child process.In case it is true, process would be started using windows shell and would be assigned its own standard error and output (we would deal with this in the next section).In such cases reading from StandardError stream throws exception.
This whole thing was not useful for me as I wanted to redirect the error stream of my top level console process (i.e. there was only one process and no parent spawning child).
Redirection in case of a top level process
By top level process I mean a process started by windows shell (i.e. the ones we start by double clicking a .exe file).Console.SetErorr method in Console class seems to do something similar.Basically it takes a TextWriter and makes that new standard error.At first look it seems we got our solution but that is not the case.It just writes anything written specifically to Console.Error stream (e.g. using Console.Error.Write) to the redirected stream but any exceptions coming from your code or third party dlls will still go to Console.
After struggling a little I realized that there is NO direct way of doing this using .NET framework libraries (In case any of you know a way, let me know ).So how do we do this ?
Answer is to do this via PInvoke to SetStdHandle windows kernel32.dll method.So in case you want to totally redirect all your errors use something like below.
[DllImport("Kernel32.dll", SetLastError = true)] public static extern int SetStdHandle(int device, IntPtr handle); public static void RedirectStandardErrorToFile(FileStream fileStream) { StreamWriter errStream = new StreamWriter(fileStream); errStream.AutoFlush = true; Console.SetError(errStream); var status = SetStdHandle(-12, fileStream.SafeFileHandle.DangerousGetHandle()); // set stderr }
SetStdHandle first parameter specifies which stream to redirect i.e. –12 is for stderr and –11 for stdout.Notice that we also use same stream in Console.SetError.
Also all this applies in case you want to redirect standard output or both.
One disadvantage of using this is that you application is now tied to windows platform i.e. you cannot use it with for example with mono on Linux.
Also, If you are someone extensively working on .NET console applications or are interested to know more than just the basics than there is an excellent pluralsight course on building console application in .NET which you might want to look into.
Normally a .NET console application writes its exception messages directly to the console so that the user can view them.
Here’s an example:
static void Main(string[] args) { RunStandardErrorRedirectExample(); Console.ReadKey(); } private static void RunStandardErrorRedirectExample() { try { double res = Divide(100, 0); Console.WriteLine(res); } catch (Exception ex) { using (TextWriter errorWriter = Console.Error) { errorWriter.WriteLine(ex.Message); } } } private static double Divide(int divideWhat, int divideBy) { return divideWhat / divideBy; }
You’ll get “Attempted to divide by 0” in the console.
However, this is not the only option you have. The standard error output channel can be overridden.
All you need is an object which derives from the abstract TextWriter class. There are a couple of classes in .NET that derive from this base class, such as StringWriter which stores the text in a StringBuilder object and StreamWriter which saves the text to a file.
We’ll look at an example using StreamWriter, i.e. we’ll tell the console to “write the lines” to a file instead of the default console. The Console.SetError method is the most important method to remember if you want to redirect the standard error output.
The following example will put the exception messages to a file called errors.txt:
private static void RunStandardErrorRedirectExample() { FileInfo exceptionsFile = new FileInfo(@"c:errors.txt"); TextWriter exceptionWriter = new StreamWriter(exceptionsFile.FullName); Console.SetError(exceptionWriter); try { double res = Divide(100, 0); Console.WriteLine(res); } catch (Exception ex) { using (TextWriter errorWriter = Console.Error) { errorWriter.WriteLine(ex.Message); } } }
If you’d like to reset the error output to the console again then you can do it as follows:
Console.SetError(new StreamWriter(Console.OpenStandardError()));
View all various C# language feature related posts here.
Hello world/Standard error
You are encouraged to solve this task according to the task description, using any language you may know.
A common practice in computing is to send error messages
to a different output stream than normal text console messages.
The normal messages print to what is called «standard output» or «standard out».
The error messages print to «standard error».
This separation can be used to redirect error messages to a different place than normal messages.
- Task
Show how to print a message to standard error by printing Goodbye, World! on that stream.
11l[edit]
Translation of: Python
:stderr.write("Goodbye, World!n")
4DOS Batch[edit]
AArch64 Assembly[edit]
.equ STDERR, 2 .equ SVC_WRITE, 64 .equ SVC_EXIT, 93 .text .global _start _start: stp x29, x30, [sp, -16]! mov x0, #STDERR ldr x1, =msg mov x2, 15 mov x8, #SVC_WRITE mov x29, sp svc #0 // write(stderr, msg, 15); ldp x29, x30, [sp], 16 mov x0, #0 mov x8, #SVC_EXIT svc #0 // exit(0); msg: .ascii "Goodbye World!n"
Ada[edit]
with Ada.Text_IO; use Ada.Text_IO; procedure Goodbye_World is begin Put_Line (Standard_Error, "Goodbye, World!"); end Goodbye_World;
Agena[edit]
io.write( io.stderr, "Goodbye, World!n" )
Aime[edit]
v_text("Goodbye, World!n");
ALGOL 68[edit]
The procedures print and printf output to stand out,
whereas put and putf can output to any open file, including stand error.
Works with: ALGOL 68 version Revision 1 — no extensions to language used
Works with: ELLA ALGOL 68 version Any (with appropriate job cards) — tested with release 1.8-8d — note that printf and putf were not ported into ELLA’s libraries.
main:( put(stand error, ("Goodbye, World!", new line)) )
Goodbye, World!
Argile[edit]
use std eprint "Goodbye, World!"
or
use std eprintf "Goodbye, World!n"
or
use std fprintf stderr "Goodbye, World!n"
ARM Assembly[edit]
Works with: as version Raspberry Pi
/* ARM assembly Raspberry PI */ /* program hellowordLP.s */ .data szMessage: .asciz "Goodbye world. n " @ error message .equ LGMESSAGE, . - szMessage @ compute length of message .text .global main main: mov r0, #2 @ output error linux ldr r1, iAdrMessage @ adresse of message mov r2, #LGMESSAGE @ sizeof(message) mov r7, #4 @ select system call 'write' swi #0 @ perform the system call mov r0, #0 @ return code mov r7, #1 @ request to exit program swi #0 @ perform the system call iAdrMessage: .int szMessage
Arturo[edit]
ATS[edit]
implement main0 () = fprint (stderr_ref, "Goodbye, World!n")
AutoHotkey[edit]
requires AutoHotkey_N
implementation.
; c:> autohotkey.exe stderr.ahk 2> error.txt FileAppend, Goodbye`, World!, stderr ; requires AutoHotkey_N
Or with the current AutoHotkey_L:
(documentation on this behavior: http://www.autohotkey.net/~Lexikos/AutoHotkey_L/docs/commands/FileAppend.htm)
FileAppend, Goodbye`, World!, *
AutoIt[edit]
ConsoleWriteError("Goodbye, World!" & @CRLF)
Avail[edit]
Error: "Goodbye, World!";
AWK[edit]
To print a message to standard error,
pipe it through a shell command:
BEGIN { print "Goodbye, World!"| "cat 1>&2" }
Or write to /dev/stderr:
BEGIN { print "Goodbye, World!" > "/dev/stderr" }
With gawk, mawk and nawk: a special feature
associates «/dev/stderr» with standard error.
The manuals of gawk and mawk describe this feature;
nawk also has this feature.
Other implementations might try to open /dev/stderr as a file.
Some Unix clones, like BSD, have a /dev/stderr device node
that duplicates standard error, so this code would still work.
Some systems have no such device node, so this code would fail.
We recommend «cat 1>&2», which is more portable, and works with any Unix clone.
BASIC[edit]
ON ERROR GOTO ManejoErrores ERROR 99 END ManejoErrores: PRINT "Googbye World!" RESUME
BaCon[edit]
BASIC256[edit]
onerror errortrap throwerror 99 end errortrap: print "Goodbye World!" return
ZX Spectrum Basic[edit]
On the ZX Spectrum, standard error is on stream 1:
10 PRINT #1;"Goodbye, World!" 20 PAUSE 50: REM allow time for the user to see the error message
Batch File[edit]
1>&2 echo Goodbye, World!
The redirection operator 1>&2
causes all output on stream 1 (standard out) to be redirected to stream 2 (standard error).
The redirection can be moved to the end of the line, too.
BBC BASIC[edit]
The program must be compiled as a console application for this to work.
STD_ERROR_HANDLE = -12 SYS "GetStdHandle", STD_ERROR_HANDLE TO @hfile%(1) PRINT #13, "Goodbye, World!" QUIT
Blade[edit]
import io io.stderr.write('Goodbye, World!')
C[edit]
Unlike puts(), fputs() does not append a terminal newline.
#include <stdio.h> int main() { fprintf(stderr, "Goodbye, "); fputs("World!n", stderr); return 0; }
C#[edit]
static class StdErr { static void Main(string[] args) { Console.Error.WriteLine("Goodbye, World!"); } }
C++[edit]
#include <iostream> int main() { std::cerr << "Goodbye, World!n"; }
Clojure[edit]
(binding [*out* *err*] (println "Goodbye, world!"))
CLU[edit]
start_up = proc () stream$putl(stream$error_output(), "Goodbye, World!") end start_up
CMake[edit]
Most messages go to standard error.
message("Goodbye, World!")
The message cannot be a keyword; message("STATUS")
never prints «STATUS», but message("" "STATUS")
does work.
COBOL[edit]
Using fixed format.
program-id. ehello. procedure division. display "Goodbye, world!" upon syserr. stop run.
CoffeeScript[edit]
Translation of: JavaScript
console.warn "Goodbye, World!"
Common Lisp[edit]
(format *error-output* "Goodbye, world!~%")
D[edit]
import std.stdio; void main () { stderr.writeln("Goodbye, World!"); }
Alternative Version[edit]
import tango.io.Stdout; void main () { Stderr("Goodbye, World!").newline; }
Dart[edit]
import 'dart:io'; void main() { stderr.writeln('Goodbye, World!'); }
Delphi[edit]
program Project1; {$APPTYPE CONSOLE} begin WriteLn(ErrOutput, 'Goodbye, World!'); end.
Dylan.NET[edit]
Works with: Mono version 2.6.7
Works with: Mono version 2.10.x
Works with: Mono version 3.x.y
Works with: .NET version 3.5
Works with: .NET version 4.0
Works with: .NET version 4.5
One Line version:
Console::get_Error()::WriteLine("Goodbye World!")
Goodbye World Program:
//compile using the new dylan.NET v, 11.5.1.2 or later //use mono to run the compiler #refstdasm mscorlib.dll import System assembly stderrex exe ver 1.1.0.0 class public Program method public static void main() Console::get_Error()::WriteLine("Goodbye World!") end method end class
Déjà Vu[edit]
!write-fragment!stderr !encode!utf-8 "Goodbye, World!n"
E[edit]
stderr.println("Goodbye, World!")
Elixir[edit]
IO.puts :stderr, "Goodbye, World!"
Emacs Lisp[edit]
In batch mode, message
actually prints to standard error:
(message "Goodbye, World!")
For greater control, princ
can be used with a special printing function:
(princ "Goodbye, World!n" 'external-debugging-output)
Erlang[edit]
io:put_chars(standard_error, "Goodbye, World!n").
Euphoria[edit]
puts(2,"Goodbye, world!n") -- 2 means output to 'standard error'
F#[edit]
eprintfn "%s" "Goodbye, World!"
or you can use the .Net classes
System.Console.Error.WriteLine("Goodbye, World!");
Factor[edit]
Start Factor in a terminal for this:
error-stream get [ "Goodbye, World! bbl, crashing" print flush ] with-output-stream*
Fantom[edit]
class Main { public static Void main () { Env.cur.err.printLine ("Goodbye, World!") } }
Forth[edit]
outfile-id stderr to outfile-id ." Goodbye, World!" cr to outfile-id
Fortran[edit]
Normally standard error is associated with the unit 0
but this could be different for different vendors.
Therefore since Fortran 2003 there’s an intrinsic module
which defines the parameter ERROR_UNIT.
program StdErr ! Fortran 2003 use iso_fortran_env ! in case there's no module iso_fortran_env ... !integer, parameter :: ERROR_UNIT = 0 write (ERROR_UNIT, *) "Goodbye, World!" end program StdErr
FreeBASIC[edit]
' FB 1.05.0 Win64 Open Err As #1 Print #1, "Goodbye World!" Close #1 Sleep
Frink[edit]
staticJava["java.lang.System","err"].println["Goodbye, World!"]
Genie[edit]
[indent=4] /* Hello, to Standard error, in Genie valac helloStderr.gs */ init stderr.printf("%sn", "Goodbye, World!")
prompt$ ./helloStderr | wc Goodbye, World! 0 0 0
Go[edit]
Built in println now goes to stderr.
package main func main() { println("Goodbye, World!") }
but the builtin print() and println() functions are not guaranteed to stay in the language. So you should probably use
package main import ("fmt"; "os") func main() { fmt.Fprintln(os.Stderr, "Goodbye, World!") }
Groovy[edit]
System.err.println("Goodbye, World!")
Haskell[edit]
import System.IO main = hPutStrLn stderr "Goodbye, World!"
Huginn[edit]
#! /bin/sh exec huginn --no-argv -E "${0}" "${@}" #! huginn import OperatingSystem as os; main() { os.stderr().write( "Goodbye, World!n" ); return ( 0 ); }
Icon and Unicon[edit]
procedure main() write(&errout, "Goodbye World" ) end
J[edit]
stderr =: 1!:2&4 stderr 'Goodbye, World!'
Java[edit]
public class Err{ public static void main(String[] args){ System.err.println("Goodbye, World!"); } }
JavaScript[edit]
and only with cscript.exe
WScript.StdErr.WriteLine("Goodbye, World!");
console.warn("Goodbye, World!")
console.error("Goodbye, World!")//only works if console object exists
OR
throw new Error("Goodbye, World!")//Should work in any browser
jq[edit]
jq -n —-arg s 'Goodbye, World!' '$s | stderr | empty'
`stderr` copies its input to STDERR before passing it along the pipeline, and hence the occurrence of `empty` above.
Julia[edit]
println(STDERR, "Goodbye, World!")
Kotlin[edit]
fun main(args: Array<String>) { System.err.println("Goodbye, World!") }
Lang[edit]
fn.errorln(Goodbye, World!)
langur[edit]
writelnErr "goodbye, people"
Lasso[edit]
define stderr(s::string) => { file_stderr->writeBytes(#s->asBytes) } stderr('Goodbye, World!')
Lingo[edit]
- Windows:
-- print to standard error stdErr("Goodbye, World!", TRUE) -- print to the Windows debug console (shown in realtime e.g. in Systernal's DebugView) dbgPrint("Goodbye, World!")
- Mac OS X:
sx = xtra("Shell").new() -- print to standard error sx.shell_cmd("echo Goodbye, World!>&2") -- print to system.log (shown in realtime e.g. in Konsole.app) sx.shell_cmd("logger Goodbye, World!")
LLVM[edit]
; This is not strictly LLVM, as it uses the C library function "printf". ; LLVM does not provide a way to print values, so the alternative would be ; to just load the string into memory, and that would be boring. ; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps %struct._iobuf = type { i8* } $"message" = comdat any @"message" = linkonce_odr unnamed_addr constant [17 x i8] c"Goodbye, world!A0", comdat, align 1 ;-- For discovering stderr (io pipe 2) declare %struct._iobuf* @__acrt_iob_func(i32) ;--- The declaration for the external C fprintf function. declare i32 @fprintf(%struct._iobuf*, i8*, ...) define i32 @main() { ;-- load stderr %1 = call %struct._iobuf* @__acrt_iob_func(i32 2) ;-- print the message to stderr with fprintf %2 = call i32 (%struct._iobuf*, i8*, ...) @fprintf(%struct._iobuf* %1, i8* getelementptr inbounds ([17 x i8], [17 x i8]* @"message", i32 0, i32 0)) ;-- exit ret i32 0 }
Goodbye, world!
Logtalk[edit]
The stream alias «user_error» can be used to print to the «standard error» stream.
:- object(error_message). % the initialization/1 directive argument is automatically executed % when the object is compiled and loaded into memory: :- initialization(write(user_error, 'Goodbye, World!n')). :- end_object.
Lua[edit]
io.stderr:write("Goodbye, World!n")
m4[edit]
errprint(`Goodbye, World! ')dnl
MANOOL[edit]
{{extern "manool.org.18/std/0.3/all"} in Err.WriteLine["Goodbye, World!"]}
Maple[edit]
Mathematica / Wolfram Language[edit]
Write[Streams["stderr"], "Goodbye, World!"]
MATLAB / Octave[edit]
This prints to standard error, and continues execution
fprintf(2,'Goodbye, World!')
This will not stop further execution, if called from within a script or function.
Mercury[edit]
:- module hello_error. :- interface. :- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. main(!IO) :- io.stderr_stream(Stderr, !IO), io.write_string(Stderr, "Goodbye, World!n", !IO).
Metafont[edit]
Metafont has no a real way to send a text to the standard output/error nor to a file. Anyway it exists the errmessage
command which will output an error message and prompt the user for action (suspending the interpretation of the source).
errmessage "Error"; message "...going on..."; % if the user decides to go on and not to stop % the program because of the error.
ML/I[edit]
MCSET S4=1 MCNOTE Goodbye, World!
Modula-2[edit]
MODULE HelloErr; IMPORT StdError; BEGIN StdError.WriteString('Goodbye, World!'); StdError.WriteLn END HelloErr.
Modula-3[edit]
MODULE Stderr EXPORTS Main; IMPORT Wr, Stdio; BEGIN Wr.PutText(Stdio.stderr, "Goodbye, World!n"); END Stderr.
N/t/roff[edit]
The request .tm
prints whatever after it, until and including the newline character, to the standard error. The string parsed to it need not be quoted and will never appear on standard output.
Neko[edit]
/** Hello world, to standard error, in Neko Tectonics: nekoc hello-stderr.neko neko hello-stderr */ /* Assume stderr is already open, just need write */ var file_write = $loader.loadprim("std@file_write", 4); /* Load (and execute) the file_stderr primitive */ var stderr = $loader.loadprim("std@file_stderr", 0)(); file_write(stderr, "Goodbye, World!n", 0, 16);
prompt$ nekoc hello-stderr.neko prompt$ neko hello-stderr Goodbye, World! prompt$ neko hello-stderr 2>/dev/null prompt$
Nemerle[edit]
System.Console.Error.WriteLine("Goodbye, World!");
NetRexx[edit]
/* NetRexx */ options replace format comments java crossref savelog symbols binary System.err.println("Goodbye, World!")
Nim[edit]
stderr.writeln "Hello World"
Oberon-2[edit]
Oxford Oberon-2
MODULE HelloErr; IMPORT Err; BEGIN Err.String("Goodbye, World!");Err.Ln END HelloErr.
Goodbye, World!
Objective-C[edit]
In Objective-C one can use the standard C library and the stderr as in the C language; nonetheless a common way to output to stderr for logging purpose and/or error notification is the NSLog function, that works almost like fprintf(stderr, «…»), save for the fact that the format string
is an NSString object, and it also prepends a timestamp.
#import <Foundation/Foundation.h> int main() { fprintf(stderr, "Goodbye, World!n"); fputs("Goodbye, World!n", stderr); NSLog(@"Goodbye, World!"); return 0; }
OCaml[edit]
prerr_endline "Goodbye, World!"; (* this is how you print a string with newline to stderr *) Printf.eprintf "Goodbye, World!n"; (* this is how you would use printf with stderr *)
we can also use the out_channel stderr:
output_string stderr "Goodbye, World!n"; Printf.fprintf stderr "Goodbye, World!n";
finally the Unix module also provides unbuffered write functions:
let msg = "Goodbye, World!n" in ignore(Unix.write Unix.stderr msg 0 (String.length msg)) ;;
Octave[edit]
fprintf(stderr, "Goodbye, World!n");
Oforth[edit]
System.Err "Goodbye, World!" << cr
Ol[edit]
(print-to stderr "Goodbye, World!")
ooRexx[edit]
ooRexx provides a .error object that writes output to the standard error stream.
.error~lineout("Goodbye, World!")
The .error object is a proxy that delegates to a backing stream, so this might be redirected.
By default, this delegates to the .stderr object, which can also be used directly.
.stderr~lineout("Goodbye, World!")
or in ‘Classic REXX style’
/* REXX --------------------------------------------------------------- * 07.07.2014 Walter Pachl * 12.07.2014 WP see Discussion where redirection from within the program is shown *--------------------------------------------------------------------*/ Say 'rexx serr 2>err.txt directs the stderr output to the file err.txt' Call lineout 'stderr','Good bye, world!' Call lineout ,'Hello, world!' Say 'and this is the error output:' 'type err.txt'
Oz[edit]
functor import Application System define {System.showError "Goodbye, World!"} {Application.exit 0} end
PARI/GP[edit]
Pascal[edit]
program byeworld; begin writeln(StdErr, 'Goodbye, World!'); end.
Perl[edit]
warn "Goodbye, World!n";
Or:
print STDERR "Goodbye, World!n";
Phix[edit]
puts(2,"Goodbye, World!")
PHP[edit]
fprintf(STDERR, "Goodbye, World!n");
or
file_put_contents("php://stderr","Hello World!n");
Picat[edit]
println(stderr,"Goodbye, World!")
PicoLisp[edit]
(out 2 (prinl "Goodbye, World!"))
Pike[edit]
werror("Goodbye, World!");
PL/I[edit]
display ('Goodbye, World');
PostScript[edit]
(%stderr) (w) file dup (Goodbye, World! ) writestring closefile
PowerBASIC[edit]
PowerShell[edit]
Since PowerShell has a slightly different system of pipes and streams
(to facilitate easy usage from a host application) the
standard Write-Error cmdlet is mainly for sending annotated error messages
to the host:
Write-Error "Goodbye, World!"
Note that this outputs more than just the message,
because behind the scenes it is an uncaught exception:
Write-Error "Goodbye, World!" : Goodbye, World! + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException
To accurately reproduce the behavior of other languages one has to resort to .NET in this case:
[Console]::Error.WriteLine("Goodbye, World!")
PureBasic[edit]
ConsoleError() writes the message string (plus a newline) to the standard error output of current program.
Standard error output can be used in conjunction with ReadProgramError() to reads a line from an other programs error output (stderr).
ConsoleError("Goodbye, World!")
Python[edit]
Works with: Python version 2.x
import sys print >> sys.stderr, "Goodbye, World!"
Works with: Python version 3.x
import sys print("Goodbye, World!", file=sys.stderr)
Works with either:
import sys sys.stderr.write("Goodbye, World!n")
R[edit]
cat("Goodbye, World!", file=stderr())
Ra[edit]
class HelloWorld **Prints "Goodbye, World!" to standard error** on start print to Console.error made !, "Goodbye, World!"
Racket[edit]
(eprintf "Goodbye, World!n")
Raku[edit]
(formerly Perl 6)
Retro[edit]
'Goodbye,_World! '/dev/stderr file:spew
REXX[edit]
version 1[edit]
This version will work with those operating systems (hosts)
that support stream output and a STDERR output
stream (by name).
If the stderr name is supported and enabled, the output is written to the terminal.
If not supported or disabled, the output is written to a (disk) file named STDERR.
call lineout 'STDERR', "Goodbye, World!"
version 2[edit]
Same as above, but uses a different style and also invokes charout instead of lineout.
msgText = 'Goodbye, World!' call charout 'STDERR', msgText
version 3[edit]
This works on Windows 7 and ooRexx and REGINA
/* REXX --------------------------------------------------------------- * 07.07.2014 Walter Pachl * enter the appropriate command shown in a command prompt. * "rexx serr.rex 2>err.txt" * or "regina serr.rex 2>err.txt" * 2>file will redirect the stderr stream to the specified file. * I don't know any other way to catch this stream *--------------------------------------------------------------------*/ Parse Version v Say v Call lineout 'stderr','Good bye, world!' Call lineout ,'Hello, world!' Say 'and this is the error output:' 'type err.txt'
version 4[edit]
ARexx with tracing console
/**/ Address command tco Call writeln stderr,'Good bye, world!' Call writeln stdout,'Hello, world!'
Ring[edit]
fputs(stderr,"Goodbye, World!")
Ruby[edit]
STDERR.puts "Goodbye, World!"
The following also works, unless you have disabled warnings (ruby command line option «-W0» or set $VERBOSE=nil
)
Run BASIC[edit]
html "<script> window.open('','error_msg',''); document.write('Goodbye, World!'); </script>""
Run Basic runs in a browser.
This opens a new browser window,
or a tab in the case of Chrome and some others.
Rust[edit]
fn main() { eprintln!("Hello, {}!", "world"); }
or
fn main() { use ::std::io::Write; let (stderr, errmsg) = (&mut ::std::io::stderr(), "Error writing to stderr"); writeln!(stderr, "Bye, world!").expect(errmsg); let (goodbye, world) = ("Goodbye", "world"); writeln!(stderr, "{}, {}!", goodbye, world).expect(errmsg); }
or
fn main() { use std::io::{self, Write}; io::stderr().write(b"Goodbye, world!").expect("Could not write to stderr"); // With some finagling, you can do a formatted string here as well let goodbye = "Goodbye"; let world = "world"; io::stderr().write(&*format!("{}, {}!", goodbye, world).as_bytes()).expect("Could not write to stderr"); // Clearly, if you want formatted strings there's no reason not to just use writeln! }
S-lang[edit]
() = fputs("Goodbye, World!n", stderr);
Salmon[edit]
standard_error.print("Goodbye, World!n");
or
include "short.salm"; stderr.print("Goodbye, World!n");
or
include "shorter.salm"; err.print("Goodbye, World!n");
or
include "shorter.salm"; se.print("Goodbye, World!n");
Sather[edit]
class MAIN is main is #ERR + "Hello World!n"; end; end;
Scala[edit]
Ad hoc REPL solution[edit]
Ad hoc solution as REPL script:
Console.err.println("Goodbye, World!")
Via Java runtime[edit]
This is a call to the Java run-time library. Not recommendated.
System.err.println("Goodbye, World!")
Via Scala Console API[edit]
This is a call to the Scala API. Recommendated.
Console.err.println("Goodbye, World!")
Short term deviation to err[edit]
Console.withOut(Console.err) { println("This goes to default _err_") }
Long term deviation to err[edit]
println ("Out not deviated") Console.setOut(Console.err) println ("Out deviated") Console.setOut(Console.out) // Reset to normal
Scheme[edit]
(error "Goodbye, World!")
Scilab[edit]
sed[edit]
Requires /dev/stderr
#n 1 { s/.*/Goodbye, World!/w /dev/stderr }
This program requires at least 1 line of input.
It changes the first line to «Goodbye, World!»
and then prints the first line to standard error.
It reads and ignores the remaining lines.
$ echo a | sed -f error.sed >/dev/null Goodbye, World!
Seed7[edit]
$ include "seed7_05.s7i"; const proc: main is func begin writeln(STD_ERR, "Goodbye, World!"); end func;
Sidef[edit]
STDERR.println("Goodbye, World!");
Slate[edit]
inform: 'Goodbye, World!' &target: DebugConsole.
Slope[edit]
(write "Goodbye, world!" stderr)
Smalltalk[edit]
The details on to which name stderr is bound may vary between Smalltalk dialects. If different, a «Smalltalk at:#Stderr put:<name your stream here>» should provide compatibility.
Stderr nextPutAll: 'Goodbye, World!'
However, all Smalltalks provide a console named «Transcript», where diagnostics is usually sent to (which is convenient, if there is no stderr to look at, as when started in Windows as an exe, vs. a com).
Thus:
Transcript show: 'Goodbye, World!'
will work on all, and is the preferred way to do this.
(and yes, when running UI-less as a console program, the global «Transcript» is usually bound to the stderr stream).
The above tells the stream to write a string;
you can also tell the string to print itself onto some stream:
'Goodbye, World!' printOn: Stderr
Both have the same effect.
SNOBOL4[edit]
terminal = "Error" output = "Normal text" end
Standard ML[edit]
TextIO.output (TextIO.stdErr, "Goodbye, World!n")
Swift[edit]
import Foundation let out = NSOutputStream(toFileAtPath: "/dev/stderr", append: true) let err = "Goodbye, World!".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) out?.open() let success = out?.write(UnsafePointer<UInt8>(err!.bytes), maxLength: err!.length) out?.close() if let bytes = success { println("nWrote (bytes) bytes") }
Goodbye, World! Wrote 15 bytes
Tcl[edit]
puts stderr "Goodbye, World!"
Transact-SQL[edit]
RAISERROR 'Goodbye, World!', 16, 1
True BASIC[edit]
CAUSE error 1, "Goodbye World!" END
TUSCRIPT[edit]
$$ MODE TUSCRIPT PRINT/ERROR "hello world" text="goodbye world" PRINT/ERROR text
@@@@@@@@ hello world @@@@@@@@ @@@@@@@@ goodbye world @@@@@@@@
UNIX Shell[edit]
echo "Goodbye, World!" >&2
C Shell[edit]
echo "Goodbye, World!" >/dev/stderr
This requires /dev/stderr
, a device node from BSD
and some other Unix clones.
This command works with both Bourne Shell and C Shell.
Ursa[edit]
out "goodbye, world!" endl console.err
VBA[edit]
Sub StandardError() Debug.Print "Goodbye World!" End Sub
VBScript[edit]
Must work in cscript.exe
WScript.StdErr.WriteLine "Goodbye, World!"
Verbexx[edit]
@STDERR "Goodbye, World!n";
Visual Basic .NET[edit]
Module Module1 Sub Main() Console.Error.WriteLine("Goodbye, World!") End Sub End Module
WDTE[edit]
io.writeln io.stderr 'Goodbye, World!';
Wren[edit]
Fiber.abort("Goodbye, World!")
X86 Assembly[edit]
Works with: nasm version 2.05.01
This is known to work on Linux, it may or may not work on other Unix-like systems
Note that it is only 2 characters different from the Assembly example on User Output — text
Prints «Goodbye, World!» to stderr (and there is probably an even simpler version):
section .data msg db 'Goodbye, World!', 0AH len equ $-msg section .text global _start _start: mov edx, len mov ecx, msg mov ebx, 2 mov eax, 4 int 80h mov ebx, 1 mov eax, 1 int 80h
XLISP[edit]
(DISPLAY "Goodbye, World!" *ERROR-OUTPUT*)
XPL0[edit]
The terms «standard output» and «standard error» are not used,
but it’s trivial to send messages to a variety of devices
by specifying their numbers.
Normally messages are displayed on the text console, which is device 0.
Instead, this example sends the message to the (first) printer,
which is device 2.
code Text=12; Text(2, "Goodbye, World!")
Yabasic[edit]
Zig[edit]
const std = @import("std"); pub fn main() !void { try std.io.getStdErr().writer().writeAll("Goodbye, World!n"); // debug messages are also printed to stderr //std.debug.print("Goodbye, World!n"); }
zkl[edit]
File.stderr.writeln("Goodbye, World!")
Display & Redirect Output
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 send their text to thee 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 Standard 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
Note: | The commandstest.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 START
ed 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
andDIR > filename.txt
are identical,ECHO Hello world>filename.txt
andECHO Hello world > filename.txt
are not, even though they are both valid.
It is not ok to use spaces in>>
or2>
or2>&1
or1>&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 textHello world
(without the trailing «2») on screen (CMD.EXE would interpret it asECHO Hello world 2>file.txt
).
In Windows XP the result is no text on screen and file.txt containing the lineHello 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
- Redirection overview page
- Use the TEE command to display on screen and simultaneously redirect to file
page last modified: 2016-09-19