basicbatch
basicbatch

Reputation: 3

How to save/load string value with a space of an environment variable to/from a file?

So I am trying to save and load an environment variable of which string value has a space in a batch file. The code works correctly if a variable doesn't have a space, but after closing the program and loading a previous save from file the variable with a space does not display correctly.

Here is the gist of what I'm trying to do:

@echo off
setlocal enabledelayedexpansion

:menu
cls
echo What do you want to do?
echo 1. Set Variables
echo 2. Save and Exit
echo 3. Load
echo 4. Display
set /p input=
    if %input%==1 goto set
    if %input%==2 goto save
    if %input%==3 goto load
    if %input%==4 goto display

:set
set "a=apples"
set "b=big bananas"
goto display

:display
echo %a%
echo %b%
pause
goto menu

:save
(echo a=%a%)>>fruit.sav
(echo b=%b%)>>fruit.sav
echo saved!
pause
exit

:load
for /f %%a in (fruit.sav) do set %%a
goto display

In the example given, if the file is saved and then loaded, the variable reference %b% ends up echoing back as just big.

Are there any suggestions on why this isn't working correctly?

Upvotes: 0

Views: 89

Answers (1)

user9165261
user9165261

Reputation:

In your for loop you have to add "tokens=*", like for /f "tokens=*" %%a in (fruit.sav) do set %%a in order to read the whole line. You could also set "delims=". (As you can see, normally /F reads until line end or space)

Upvotes: 1

Related Questions