Redirection - optionally

  • Thread starter Thread starter Jeff F
  • Start date Start date
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
 
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.
 
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%
 
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
 
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.
[
 
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.
 
Back
Top