Search code examples
batch-filestderr

Programmatically writing a batch file to echo to stderr


As a part of some integration tests I am working on, I need to write a batch file that echoes out to stderr on a windows box. Currently I am using the following command:

md %UserProfile%\tests\e3f949d1219d4cad9288bf88d0fcc906\ && cd %UserProfile%\tests\e3f949d1219d4cad9288bf88d0fcc906\ && ( echo @echo off  && echo 'echo This is error line 1 1>&2' && echo 'echo This is error line 2 1>&2' && echo @echo on ) >>test-stderrout.bat

This should create a temp directory under the %UserProfile%\tests\ directory. Then Navigate to this temp working directory. Then create a batch file with the following code:

@echo off
echo This is error line 1 1>&2
echo This is error line 2 1>&2
@echo on

However, instead the file contains:

@echo off
@echo on

I see that the first echo gets piped out into stderr instead of reading that as text to then be in the batch file. Is it possible to to escape this somehow to allow the output to contain the redirect statement?


Solution

  • The following line should do what you want:

    md "%UserProfile%\tests\e3f949d1219d4cad9288bf88d0fcc906\" && cd /D "%UserProfile%\tests\e3f949d1219d4cad9288bf88d0fcc906\" && ((echo @echo off) & (echo echo This is error line 1 1^>^&2) & (echo echo This is error line 2 1^>^&2) & (echo @echo on)) >> test-stderrout.bat
    

    Changes to your code:

    • the directory paths are enclosed in "" to avoid trouble with whitespaces;
    • switch /D is added to cd to change also the drive if necessary (I don't know your current drive);
    • the >& in your echo lines are escaped like ^>^& to be echoed literally;
    • each echo command is enclosed within () to avoid trailing spaces;
    • && (conditional command separator) are replaced by & (unconditional command separator) because && does not make sense between the echo commands; I kept it at md and cd to avoid echoing in case the directory could not be created for some reason;