1

I've noticed some very strange behaviour when trying to write text to a file without having the trailing new line. There is code everywhere which looks like that:

echo|set /p=foo > foo.txt

It works great but my build system fails on that because when I evaluate %ERRORLEVEL% I get a 1 after the call:

echo %ERRORLEVEL%
echo |set /p=foo>foo.txt
echo %ERRORLEVEL%

returns

D:\>echo 0
0

D:\>echo   | set /p=foo  1>foo.txt

D:\>echo 1
1

Is this a known behaviour? Is set getting picky because there is no variable to set?

Note: The echoed code of echo |set /p=foo>foo.txt is actually echo | set /p=foo 1>foo.txt

1
  • 1
    As far as I know, that is the case. set /p will set errorlevel to 1 because no input is given, whether you use a variable or not.
    – Regejok
    Commented Jun 29, 2017 at 16:10

2 Answers 2

1

Thanks @Regejok for the hint. Searching for set is not the easiest task though :D

However citing this source: https://ss64.com/nt/set.html it seems that this indeed causes error level to be set to 1:

Errorlevels

    When CMD Command Extensions are enabled (the default)

    If the variable was successfully changed %ERRORLEVEL% = 0
    No variable found/invalid name = 1
    SET /A Unbalanced parentheses = 1073750988
    SET /A Missing operand = 1073750989
    SET /A Syntax error = 1073750990
    SET /A Invalid number = 1073750991
    SET /A Number larger than 32-bits = 1073750992
    SET /A Division by zero = 1073750993
0

Just stumbled on the same issue.

After playing a little with the set /p command I found that it would rise %ERRORLEVEL% in two cases: when there is no variable name, and when user input is empty.

I used the trick to strip quotes from string, and for me providing a dummy variable name was just enough to fix:

$ echo | set /p DUMMY="Some string with spaces and quotes" > log.txt

And then checking that it actually works:

$ echo %ERRORLEVEL%
0
$ type log.txt
Some string with spaces and quotes

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .