0

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 "
  • Why is there a blank space after titi, as seen in "titi "?

  • What should be the syntax to simply get "titi"as expected?

Thanks in advance for your help!

dom_beau
  • 2,437
  • 3
  • 30
  • 59
  • Look at your `SET` command. I clearly see a space after the variable name and before the right parentheses: `( set VALUE=%_VALUE% )`. Best practice is to use this syntax: `if NOT "%_VALUE%"=="" set "VALUE=%_VALUE%"` – Squashman Oct 24 '18 at 13:56
  • @Squashman Thanks, you're right! From my C++/C/etc background I assumed `VALUE` was set to _VALUE value but actually I understand that it is set to what is on the right side of the `=` sign... ;-) – dom_beau Oct 24 '18 at 14:00
  • Would also like to add that you don't need two variables to do what you are doing. You can just use the variable `value` with the `SET /P` command. If they hit enter at the input prompt, the value will still be set to the default. – Squashman Oct 24 '18 at 14:01
  • Ah! Thanks! I'll do that. – dom_beau Oct 24 '18 at 14:03
  • @dom_beau I recommend reading also my answer on [How to stop Windows command interpreter from quitting batch file execution on an incorrect user input?](https://stackoverflow.com/a/49834019/3074564) if you want to make your batch file fail safe on accidentally or intentionally wrong user input. – Mofi Oct 24 '18 at 15:20

1 Answers1

1

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%
Squashman
  • 13,649
  • 5
  • 27
  • 36