在Windows批处理中,Linux shell命令echo -n抑制输出末尾的换行符是什么?

其思想是在循环中的同一行上写入。


当前回答

使用set和/p参数可以不带换行符进行回显:

C:\> echo Hello World
Hello World

C:\> echo|set /p="Hello World"
Hello World
C:\>

其他回答

我根据@arnep的想法做了一个函数:

echo|set /p="Hello World"

下面就是:

:SL (sameline)
echo|set /p=%1
exit /b

使用call:SL "Hello There" 我知道这没什么特别的,但我花了很长时间才想出来,所以我想我应该把它贴在这里。

使用:echo | set /p=或<NUL set /p=都可以抑制换行符。

然而,当编写更高级的脚本时,检查ERRORLEVEL变得很重要,因为设置set /p=而不指定变量名将把ERRORLEVEL设置为1,这可能是非常危险的。

一个更好的方法是使用一个虚拟变量名,就像这样: echo | set /p dummyName=Hello World

这将产生你想要的东西,没有任何偷偷摸摸的东西在后台,因为我必须找到艰难的方法,但这只适用于管道版本;<NUL set /p dummyName=Hello仍然会将ERRORLEVEL提升为1。

Late answer here, but for anyone who needs to write special characters to a single line who find dbenham's answer to be about 80 lines too long and whose scripts may break (perhaps due to user-input) under the limitations of simply using set /p, it's probably easiest to just to pair your .bat or .cmd with a compiled C++ or C-language executable and then just cout or printf the characters. This will also allow you to easily write multiple times to one line if you're showing a sort of progress bar or something using characters, as OP apparently was.

示例1:它工作并生成退出代码= 0。这很好。 注意“。”,直接在echo之后。

C:\Users\phife.狗\ gitrepos \ 1 # \ repo_abc \脚本 @echo。| set /p JUNK_VAR=这是一个像Linux echo一样显示的消息-n将显示它…&回显%ERRORLEVEL%

这是一个像Linux echo -n一样显示的消息…0

示例2:这可以工作,但产生退出代码= 1。这很糟糕。 请注意回声后面缺少“。”。这似乎就是不同之处。

C:\Users\phife.狗\ gitrepos \ 1 # \ repo_abc \脚本 @echo | set /p JUNK_VAR=这是一个像Linux echo -n会显示它的消息…&回显%ERRORLEVEL%

这是一个像Linux echo -n一样显示的消息…1

jscript:

@if (@X)==(@Y) @end /*
    @cscript //E:JScript //nologo "%~nx0" %*
    @exit /b %errorlevel%
*/if(WScript.Arguments.Count()>0) WScript.StdOut.Write(WScript.Arguments.Item(0));

如果它叫write.bat,你可以这样测试它:

call write.bat string & echo _Another_String_

如果你想使用powershell,但有cmd定义的变量,你可以使用:

set str=_My_StrinG_
powershell "Write-Host -NoNewline ""%str%""""  & echo #Another#STRING#