Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch: Why does appending a textfile write "ECHO is off" instead?

So I wrote a batch that has some code to check how many times it has been run by reading a textfile and then writing back into that textfile the new, increased number.

@ECHO OFF
for /f "delims=" %%x in (TimesRun.txt) do set Build=%%x
set Build=%Build%+1
@echo Build value : %Build%
echo %Build%>>TimesRun.txt
Pause

That does append the textfile allright, but it adds "1+1" to it. Silly me! I forgot to use the /a switch to enable arithmetic operations! But when I change the code accordingly...

@ECHO OFF
for /f "delims=" %%x in (TimesRun.txt) do set Build=%%x
set /a Build=%Build%+1
@echo Build value : %Build%
echo %Build%>>TimesRun.txt
Pause

... something funny happens: Instead of appending my file, ECHO is off. gets written on the console. Now, I know that this usually happens when ECHO is used without text or with an empty variable. I have added the first @echo Build value : %Build% specifically to see whether the variable Build is empty or not; it is not, and the calculation was carried out correctly. I already figured out that

>>TimesRun.txt (echo %Build%)

does bring the desired result. I still do not understand why

echo %Build%>>TimesRun.txt

does not, however. What am I missing?

like image 325
HerrMetik Avatar asked Aug 25 '16 13:08

HerrMetik


1 Answers

You are unintentionally specifying a redirection handle.


Redirection allows you to specify a certain handle that defines what is to be redirected:

0     = STDIN  (keyboard input)
1     = STDOUT (text output)
2     = STDERR (error text output)
3 ~ 9 = undefined

For the input redirection operator <, handle 0 is used by default; for the output redirection operators > and >>, the default handle is 1.

You can explicitly specify a handle by putting a single numeric figure in front of the redirection operator; for instance 2> defines to redirect the error text output.


In your echo command line you are doing exactly this unintentionally, when %Build% is a single numberic digit, like 1 for example:

echo 1>>TimesRun.txt

To avoid that, you have the following options:

  1. To reverse the statement so that the redirection definition comes first:

    >>TimesRun.txt echo %Build%
    

    This is the most general and secure way of doing redirections.

  2. To enclose the redirected command in parentheses:

    (echo %Build%)>>TimesRun.txt
    

    This also works safely.

  3. To put a SPACE in front of the redirection operator:

    echo %Build% >>TimesRun.txt
    

    This works too, but the additional SPACE is included in the output of echo.

See also this great post: cmd.exe redirection operators order and position.

like image 195
aschipfl Avatar answered Oct 20 '22 15:10

aschipfl