windows 如何在DOS中进行字符串比较条件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3713626/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to do string comparison condition in DOS?
提问by Haoest
Wow, never thought I would ever write anything in DOS. Now that I do, I know why I never wanted to. The syntax is absurd!
哇,从没想过我会在 DOS 中写任何东西。现在我做了,我知道为什么我从来不想。语法很荒谬!
Anyways I need help please. I would like to prompt the user for input, and if a blank line is received, I would like to use the default value, like this:
无论如何,我需要帮助。我想提示用户输入,如果收到空行,我想使用默认值,如下所示:
set name=abraham.
set /p input=please enter your name, press enter to use %name%:
if not %input%=="" set name=%input%
echo your name is %name%
I get an error says "set was unexpected at this time."
我收到一条错误消息,说“此时设置是意外的”。
Can you help please?
你能帮忙吗?
回答by Philip Rieck
Try
尝试
set name=abraham
set /p name=please enter your name, press enter to use %name%:
echo entered : %name%
Note that in cmd files, if nothing is entered, the var is not changed.
请注意,在 cmd 文件中,如果不输入任何内容,则不会更改 var。
Or, with the if:
或者,如果:
set name=abraham
set input=
set /p input=please enter your name, press enter to use %name%:
if "%input%" NEQ "" set name=%input%
echo entered : %name%
Note the quotes around input in the if statement, and notice that I am clearing out input before running (or it will hold the last value if nothing is entered by the user)
请注意 if 语句中 input 周围的引号,并注意我在运行之前清除输入(或者如果用户未输入任何内容,它将保留最后一个值)
回答by mafu
Empty strings are actually empty in shell programming, so try if "%input%"=="" set...
(with quotes) or if %input%== set...
(empty string is empty).
空字符串在 shell 编程中实际上是空的,因此请尝试if "%input%"=="" set...
(带引号)或if %input%== set...
(空字符串为空)。
回答by Metro Smurf
I believe you need to put single quotes (not sure if double or single matter) around the variable:
我相信你需要在变量周围加上单引号(不确定是双引号还是单引号):
@echo off
set name=abraham.
set /p input=please enter your name, press enter to use %name%:
if not '%input%'=='' set name=%input%
echo your name is %name%
pause