Gerold Broser
Gerold Broser

Reputation: 14762

How to echo a number from 0 to 9 in a Windows batch file to a file without trailing space?

If I do the following in a batch file named test:

echo number=0 > file

and run it:

> test
> echo number=0  1> file

file contains:

number=0␣

If I change test to:

echo number=1> file

and run it:

 > test
 > echo number= 1>file

file contains:

number=

The 1 apparently is interpreted as stdout handle, which is comprehensible.

If I change test to:

echo number=0> file

– and 2 to 9 respectively – and run it:

 > test
 > echo number= 0>file
 number=

the 0 and 2 to 9 apparently are interpreted as non-stdout handles and file is empty, which is comprehensible, too.

With:

echo "number=1"> file

file contains:

"number=1"

With:

echo (number=1)> file

file contains:

(number=1)

Upvotes: 2

Views: 3641

Answers (1)

Gerold Broser
Gerold Broser

Reputation: 14762

While writing the question I found the answer at How to avoid writing trailing spaces into text file on redirecting ECHO outputs to a file?:

Put the redirection in front of the command like:

> file echo number=0

or, as commented by Stephan, group the complete command, not just the argument:

(echo number=0) > file

(The title Using parenthesis/brackets to group expressions misses a bit, IMHO. It's to group commands and expressions, isn't it?)

Upvotes: 7

Related Questions