Windows 10

Batch File To Write Variable To a Text File

In this tutorial, you’ll learn how to write variables to a text file in a Windows batch script using the ECHO command. This technique is useful when automating logs, reports, or configurations in Windows environments.

Batch files execute a series of DOS (Disk Operating System) commands, and using redirection, you can store variable data into external files.
 
 

💡 Batch File to Write Variables to a Text File

The following batch script creates two variables, Name and Address, and writes them to a file named file.txt:

@echo off
SET Name="Alex"
echo %Name% > file.txt
SET Address="Boston"
echo %Address% >> file.txt

📁 Output:
 

 

🔍 Explanation

@echo off ➤ Suppresses command echoing for cleaner output.

SET Name="Alex" ➤ Sets the variable Name with the value “Alex”.

echo %Name% > file.txt ➤ Writes the Name value to file.txt, overwriting any existing content.

SET Address="Boston" ➤ Sets the variable Address.

echo %Address% >> file.txt ➤ Appends the Address value to the same file, preserving the content already written.
 

📌 Redirection Operators Recap
  • > – Overwrites the file with new content.
  • >> – Appends to the file without deleting existing data.

 

📚 Summary

Writing variables to a text file in batch scripts is an essential skill for automating logging and reporting tasks on Windows systems. Whether you’re saving configuration data or creating custom log files, the combination of ECHO, variables, and redirection makes it simple and effective.
 

One thought on “Batch File To Write Variable To a Text File

  • Please enlighten me with the simple batch code to open myText.txt on drive A (root), make a change or add something and save it to myTextBackup.txt on drive B and then save it back to myText.txt on drive A, full circle i.e. the two files get updated.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *