Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 296
Haoest Avatar asked Sep 14 '10 23:09

Haoest


People also ask

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

What does %% mean in DOS?

[ %% ] (Percent Percent, or Double Percent) is employed in the "FOR" command when it is used within a batch file. It represents the variable used in that command. It is followed by a single letter, although as stated above, some newer DOS versions allow multiple letters.

How do I compare strings to characters?

String comparison by Using String Library Functionstrcmp() function is used to compare two strings. The strcmp() function takes two strings as input and returns an integer result that can be zero, positive, or negative. The strcmp() function compares both strings characters.


3 Answers

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)

like image 147
Philip Rieck Avatar answered Nov 09 '22 19:11

Philip Rieck


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

like image 40
mafu Avatar answered Nov 09 '22 21:11

mafu


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
like image 1
Metro Smurf Avatar answered Nov 09 '22 20:11

Metro Smurf