Home > Software engineering >  In a batch file, how do I echo the word "on" to a text file without turning echo on?
In a batch file, how do I echo the word "on" to a text file without turning echo on?

Time:01-07

I have a settings.txt file that looks like this:

on
off

In the beginning of the batch file, various variable values are populated with these settings such as %AutoTransfer% being set to on, AutoViewLog set to on, etc. Whenever one of these settings are toggled on/off, I call the :WriteSettings function which tries to do this:

echo %AutoTransfer% > settings.txt
echo %AutoViewLog% >> settings.txt

But instead the command interpreter turns echo itself on or off. I've tried !AutoTransfer! and (!AutoTransfer!) still with no luck. Of course I can change it to using enabled/disabled values instead of on/off values but that screws up my menu that relies on these words being short. And if I resort to setting the values to be 1 for enabled and 0 for disabled, I have to write tons more code for the main menu (a bunch of "if" statements to echo "on" when the variable is 1, "off" when it is 0).

My current solution would work... it would assign values to "is on" instead of "on" and just make the word "is" part of the value of the variable so that I can use 'AutoTransfer %AutoTransfer%' on the menu to display "AutoTransfer is on". But this feels like a duct tape solution, and for the pure virtue of learning, I want to know if there is an elegant solution to this or if all solutions are just as stupid/lame/ugly as that or possibly worse.

I also can't believe I seem to be the first to ask this question. I looked for 20 minutes for anyone else who has asked this question... couldn't find a single one. Am I really the first person who ever wanted to store/read/echo super basic "on/off" values to a settings file and to the screen? Or am I just the first person who is too dumb to figure it out?

CodePudding user response:

You can use set /P to print

(
    set /P ="on" <nul
    echo(
    set /P ="off" <nul
    echo(
) > settings.txt

Alternatively store the new line in a variable and use it like this

setlocal EnableDelayedExpansion
(set \n=^
%=Do not remove this line=%
)

echo on!\n!off > settings.txt

You can also print directly using any combination to print a blank line

echo(on
echo on
echo,on
echo/on
echo;on
echo=on
echo[on
echo]on

echo(off
echo off
echo,off
echo/off
echo;off
echo=off
echo[off
echo]off

although the fastest method is probably echo(on and the reliable ones might be echo:on, echo\on as indicated by the other answer

CodePudding user response:

Use of a non-space is the usual method for doing this, such as:

echo.on>>settings.txt

This prevents the on from being treated as a command to echo rather than a string to echo.

Note though that I have no space between the on and the output redirection there. If you put the space there, it's actually added to the file which is probably not what you want.

  • Related