Prevent extra space when setting variable on Windows command line

Solution 1:

set foo=hello&& echo test

works fine over here,

echo "%foo%"

prints

"hello"

:)

Solution 2:

You can do this

set "foo=hello" && echo test

Solution 3:

As indicated by the other answers, spaces at the end of a set command are significant, so if you type

set foo=hello & echo test
or even
set foo=hello␣

(where ␣ represents a space), %foo% gets set to the six-character string h, e, l, l, o,  .

I had a similar problem with space when echoing a string to an output file.  Not surprisingly (in light of the above),

echo hello >myfile

writes the six-character string h, e, l, l, o,    (plus CR and LF) to the file, while

echo hello> myfile

does not include the space.  But spaces at the end of the command line are still a problem.  If, for some reason, you say

echo hello>myfile␣
then you get a space at the end of the output.  When I removed the space after the filename, the space at the end of the output disappeared.

Weird, but this worked for me.