首页 > 解决方案 > How to avoid extra blank space on variable value when prompted in Windows cmd batch file

问题描述

I'm experiencing a strange behaviour with a Windows batch script when I want to read a value by prompting the user. Here is my script:

echo off

set VALUE=toto
set _VALUE=
set /p _VALUE=Enter the value or leave blank to accept default (%VALUE%):

if [%_VALUE%] NEQ [] ( set VALUE=%_VALUE% )

set _VALUE=

echo "%VALUE%"

If I keep the default, here is what I get, as expected:

...>myscript.cmd
Enter the value or leave blank to accept default (toto):
"toto"

But if I enter a new value, here is what I unexpectedly get:

...>myscript.cmd
Enter the value or leave blank to accept default (toto): titi
"titi "

Thanks in advance for your help!

标签: batch-filecmd

解决方案


To fix your code, you can do this as a best practice.

@echo off

set VALUE=toto
set _VALUE=
set /p _VALUE=Enter the value or leave blank to accept default (%VALUE%):

if NOT "%_VALUE%"=="" set "VALUE=%_VALUE%"

set _VALUE=

echo "%VALUE%"

But all you really need to do is this.

set "VALUE=toto"
set /p VALUE=Enter the value or leave blank to accept default (%VALUE%):
echo %value%

推荐阅读