Redirection - optionally

J

Jeff F

I've numerous bat files of the following (much simplified) ilk:

test.bat
========

set log=%1

dir > %log%

I need to use the same bat files to redirect to a file by executing a
command:

test somefile.log

I'd also like to be able to execute the bat file _without_ any redirection
occurring.

I've tried:

test &1

Any ideas?

Thanks, Jeff
 
G

Guest

You can do this if you want the entire output from the batch file in one log
file

test.bat p1 p2... > c:\logfile.txt 2>&1

Or you can do this

set redir=^>nul 2^>^&1
if /i not X%1==X set redir=^>%1 2^>^&1
dir %redir%
set redir=

The first line sets redirection to nul
The second line checks the first parameter,
if no parameters, output is suppressed,
if the first parameter is a file, output is rediredted to the file,
if the first parameter is con, the output will go to the cdonsole.
 
W

William Allen

I've numerous bat files of the following (much simplified) ilk:

test.bat
========

set log=%1

dir > %log%

I need to use the same bat files to redirect to a file by executing a
command:

test somefile.log

I'd also like to be able to execute the bat file _without_ any redirection
occurring.

I've tried:

test &1

Any ideas?

When there is "no redirection", what really happens is that the
command processor uses the CON device (CON=console), which
reads from Keyboard and writes to Screen. Simply use the CON
device explicitly in your LOG variable if there is no parameter 1.

Then everywhere in the Batch file, redirect explicitly to %LOG%
and the Batch file will behave as if there is "no redirection" if you
don't specify a filename in %1

As a simple example, the syntax would be:

@ECHO OFF
SET LOG=%1
IF [%1]==[] SET LOG=CON
DIR>%LOG%
OtherCommands>%LOG%
 
W

William Allen

in message
....snip
As a simple example, the syntax would be:

@ECHO OFF
SET LOG=%1
IF [%1]==[] SET LOG=CON
DIR>%LOG%
OtherCommands>%LOG%

By the way, if you prefer not to add the IF [%1]==[] SET LOG=CON
line to the top of all your batch files, use CON as the first parameter
on the unedited Batch files:

YourBatch CON
 
S

Stefan Kanthak

William Allen said:
in message
[...]

By the way, if you prefer not to add the IF [%1]==[] SET LOG=CON
line to the top of all your batch files, use CON as the first parameter
on the unedited Batch files:

YourBatch CON

I prefer CON: (with explicit set colon) for sake of clarity here.
The same goes for "goto :LABEL".

Stefan

PS: your signature separator is wrong; please use "-- ", the trailing blank
IS significant.
[
 
W

William Allen

X-No-archive: yes

"William Allen" wrote: ....snip

I prefer CON: (with explicit set colon) for sake of clarity here.
The same goes for "goto :LABEL".
....snip

I don't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top