Haoest
Haoest

Reputation: 13906

How to do string comparison condition in DOS?

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!

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?

Upvotes: 5

Views: 35572

Answers (3)

Metro Smurf
Metro Smurf

Reputation: 38385

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

Upvotes: 1

Philip Rieck
Philip Rieck

Reputation: 32568

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.

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)

Upvotes: 9

mafu
mafu

Reputation: 32700

Empty strings are actually empty in shell programming, so try if "%input%"=="" set... (with quotes) or if %input%== set... (empty string is empty).

Upvotes: 2

Related Questions