Windows Batch-Script - Attempting to save variable to text file then load it back into a variable upon restart
I'm attemting to do something probably pretty easy.
I'm trying to allow users of a windows batch script to set the background colour and store it in a txt file which is then loaded into a variable each time they run the script.
So far I have:
set /p ColourOpt=<%LogPath%\%UserName%_Options.Colour.log
Which loads the contents of the .log file into the Co开发者_高级运维lourOpt variable (%username% and %logpath% are already defined and are working fine).
Then I use the following code to apply the option:
If /I '%Colouropt%'=='0f' Color 0f
If /I '%Colouropt%'=='08' Color 08
If /I '%Colouropt%'=='0c' Color 0c
If /I '%Colouropt%'=='0d' Color 0d
If /I '%Colouropt%'=='0e' Color 0e
If /I '%Colouropt%'=='0a' Color 0a
If /I '%Colouropt%'=='1a' Color 1a
If /I '%Colouropt%'=='1c' Color 1c
If /I '%Colouropt%'=='1e' Color 1e
If /I '%Colouropt%'=='1f' Color 1f
This also works fine and the colour is set without issue.
Now the problem, When i use the script to output the users colour setting to the .log file it adds spaces, which now cause the script to close instead of applying the change.
The code used to write to the .log file:
IF /I '%Options%'=='1' Echo 0f>%LogPath%\%UserName%_Options.Colour.log & Set ColourOpt=0f & Color 0f
This will save the option to the .log file and set the colour straight away, aswell as setting it in the variable.
However this outputs the text file with a space after "0f" and a blank line under it.
Is there a way to output without the spaces, or allow the if command to ignore spaces?
Any help would be greatly apreciated!
Thanks!
Why are you trying to do it as a single operation? Windows has had multi-line if
blocks for ages:
IF /I '%Options%'=='1' (
Echo 0f>%LogPath%\%UserName%_Options.Colour.log
Set ColourOpt=0f
Color 0f
)
It's actually the space preceding the first &
which is being output to the file, you could equally well fix that with:
IF /I '%Options%'=='1' Echo 0f>%blah%_Options.Colour.log& Set ColourOpt=...
(no space in there).
If you don't even want the line endings (i.e., if you want your file to consist of only 0f
), you already know half the trick:
<nul set /p junk=0f>xyz.txt& echo hello
This will create a file xyz.txt
with only those two characters - no extra space and no line ending afterwards.
See this answer for more information and all the other answers, including some more of mine, for some neat tricks.
精彩评论