11

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.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
JoerassicPark
  • 111
  • 1
  • 1
  • 6

2 Answers2

17

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
Stephan
  • 53,940
  • 10
  • 58
  • 91
  • Alternative: `echo 6 1> txt.txt`, or `@echo %var% 1>txt.txt` in the original example. Alternative way to verify the output: `type txt.txt`. – Johan Jan 06 '17 at 13:32
  • @Johan: both alternatives will write an additional space to the file (which is unnecessary and a potential trouble maker). "Real" alternatives are `(echo 6)>txt.txt` or `(echo %var%)>txt.txt – Stephan May 07 '18 at 05:27
4

Use the set command to get the contents of a file:

set /p var=<filename

Use the echo command to put into a file:

@echo Contents Of File > "FileName"

To append another line to the end of the file, use:

@echo Contents Of File >> "FileName"

Also, put the commands on separate lines or use '&&' between them on the same line.