Saving a batch variable in a text file

JoerassicPark picture JoerassicPark · Jan 25, 2015 · Viewed 41.2k times · Source

I am trying to save a batch variable into a text file. I currently have this code:

@echo off

Set var=6
@echo %var%>txt.txt

For /f "tokens*" %%i in (txt.txt) do @echo %%i
Pause

It's supposed to save the 6 into the variable var and then write the variable in a text file. I want to do this to save user input into a text file so that when the batch program is terminated it will hold the variables.

Answer

Stephan picture Stephan · Feb 1, 2015

There is a little problem with redirection. You are redirecting a "stream"; they are numbered 0-9. 0 is for "Standard Input" (STDIN), 1 is for "Standard Output" (STDOUT), 2 is for "Error Output" (STDERR).

If you use the redirection symbol > without a stream number, it defaults to "1".

So echo text>txt.txt is just an abreviation for echo text 1>txt.txt

Now it's getting tricky: echo 6>txt.txt won't echo "6" to the file, but tries to redirect "Stream 6" (which is empty) to the file. The Standard Output echo is off goes to the screen, because "Stream1" is not redirected.

Solution:

If you try to redirect a number or a string which ends with a number, just use a different syntax:

>txt.txt echo 6