batch-file - 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 "
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!
解决方案
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%
推荐阅读
- c# - 我们如何使用 c# SQL 在检查时隐藏滑块图像位置
- swift - 在 UIImage ARKit 4 上显示置信度图
- angular - 角度路由将带有片段部分的URL外部重定向到角度页面
- vba - 使用具有自动调整大小功能的 vba 添加文本框
- asynchronous - 同步与异步和阻塞与非阻塞 IO 有什么区别。他们都在谈论同一个概念吗?
- unreal-engine4 - 当主机在虚幻引擎 4 中离开游戏时如何销毁所有客户端会话
- android - 从 url 将 GIF 插入 InputConnection
- c++ - 为什么字符串可以这样使用
- java - jest- 使用 spring boot 的 elasticsearch 配置
- django - 当附件大小接近 1 mb 时 Django 不发送电子邮件 错误消息 SMTPServerDisconnected