François Beaune
François Beaune

Reputation: 4500

Move redirection instructions to variable?

Is it possible to store redirection instructions in a variable? Something along these lines:

set redirect=>> buildlog.txt 2>&1

nmake -f Makefile %redirect%

As is, this doesn't work.

Upvotes: 0

Views: 21

Answers (2)

Squashman
Squashman

Reputation: 14320

All you really need to do is use delayed expansion.

 @echo off
 set "redirect=>> buildlog.txt 2>&1"

 setlocal enabledelayedexpansion
 nmake -f Makefile !redirect!
 endlocal

Upvotes: 0

Marc B
Marc B

Reputation: 360782

Since > are shell metachars, you can't directly use them to assign to a variable a text. They'll get executed by the shell and their RESULT gets assigned. So you have to quote/escape them:

set redirect=^>^>buildlog.txt 2^>^&1
             ^-^--etc... cmd uses ^ to escape.

Which then works as you expect:

C:\temp\z>set foo=^>^>log.txt
C:\temp\z>dir %foo%
C:\temp\z>dir
 Volume in drive C is Windows7_OS
 Volume Serial Number is 0E31-0E35

 Directory of C:\temp\z

09/23/2016  10:32 AM    <DIR>          .
09/23/2016  10:32 AM    <DIR>          ..
09/23/2016  10:32 AM               333 log.txt
               1 File(s)            333 bytes
               2 Dir(s)  274,917,388,288 bytes free

C:\temp\z>type log.txt
 Volume in drive C is Windows7_OS
 Volume Serial Number is 0E31-0E35

 Directory of C:\temp\z

09/23/2016  10:32 AM    <DIR>          .
09/23/2016  10:32 AM    <DIR>          ..
09/23/2016  10:32 AM                 0 log.txt
               1 File(s)              0 bytes
               2 Dir(s)  274,917,388,288 bytes free

Upvotes: 2

Related Questions