Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving variables in a text file

Tags:

batch-file

I'm trying to load and save variables into a file.
For example:

@echo off
set /a number=1
echo %number%>text.txt

How do I store the number from the text file in a variable for example variable1?

like image 326
Richhh_y Avatar asked Dec 23 '22 00:12

Richhh_y


1 Answers

As mentioned by aschipfl, there are two ways to do it:

  1. Using set /P (redirect variable to a text file and read (the file) with set /p).
  2. Parse the file using a for /F loop.

As the first way is already mentioned by Tiw, I will only deal with the second one. You should do:

@echo off
set "number=1"
(echo %number%)>text.txt
for /F "delims= eol=" %%A IN (text.txt) do set "variable1=%%A"

Note that:

  • /a option in set is used only to perform arithmetic operations. It doesn't mean that the interpreter will 'see' this as a number.
  • The parentheses are added for security. They prevent echoing an extra space in the txt file. echo %number%>txt won't work if %number% is <10 because 0 is STDIN, 1 is STDOUT, 2 is STDERR and numbers from 3 to 9 are undefined. Apparently, it's sending STDIN/STDOUT/STDERR/UNDEFINED of nothing to a file.

Further reading:

  • https://ss64.com/nt/syntax-redirection.html
  • https://ss64.com/nt/for_f.html
  • https://ss64.com/nt/set.html
like image 88
double-beep Avatar answered Feb 15 '23 16:02

double-beep