We help IT Professionals succeed at work.

Batch file variable name for redirection

865 Views
Last Modified: 2012-05-09
I'd like to use a variable for a log file that I'm redirecting output to.


set log_file = C:\temp\mylog.txt
echo Batch is in work >> %log_file%
exit

I get a syntax error using this approach.

How can I use a variable name for the redirection?

Thanks.
Comment
Watch Question

From
http://www.computing.net/answers/dos/command-output-to-variable/7847.html

In order to redirect the output to a FILE, instead of displaying it, do:

command > file.ext
e.g.: dir > data.txt

Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Commented:
plusone3055:

I reproduce his problem locally.
The real problem was not the redirection but the "set log_file = C:\temp\mylog.txt".
The syntax should be "set log_file=C:\temp\mylog.txt"
There are 2 mistakes in your code:
1) There shouldn't be spaces in your set command around the equal sign.
2) The output redirection needs to use a single >, not a >>; >> is used for HERE files, which is something completely different.
@ECHO OFF
set log_file="C:\temp\mylog.txt"
echo "Batch is in work" > %log_file%
exit

Open in new window

Author

Commented:
Yep it was the spaces on either side of the equal sign.

Author

Commented:
colacadstink,
 > causes the file to be rewritten, whereas >> causes an append to an existing file
Also, using quotes after echo causes the quotes to be written to the file.
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.