Welcome guest. Before posting on our computer help forum, you must register. Click here it's easy and free.

Author Topic: batch string help  (Read 6908 times)

0 Members and 1 Guest are viewing this topic.

036483

  • Guest
batch string help
« on: January 07, 2012, 11:35:11 PM »
So I was trying to do the following:

set /p t=""
if %t%==joe goto num1
if %t%==two words goto num2


But when I would input the text "two words", it would complain about:

words==joe was unexpected at this time

I thought it was a issue with the space of two words, but I cant seem to fix it. any help?

Salmon Trout

  • Guest
Re: batch string help
« Reply #1 on: January 08, 2012, 02:17:57 AM »
The problem arises because of the space in "two words". You need to quote the variables and test text like below. In fact it is a good idea to always use quotes. Otherwise for example you would also get an error if you just hit Enter at the set /p line and input an empty string.

if "%t%"=="joe" goto num1
if "%t%"=="two words" goto num2



036483

  • Guest
Re: batch string help
« Reply #2 on: January 08, 2012, 02:21:36 AM »
oooooh!
You got to put quotes around the %t% too!

Ah thats why I was messing up. I tried to make it a string by putting quotes on the "two words" but that didnt work

Salmon Trout

  • Guest
Re: batch string help
« Reply #3 on: January 08, 2012, 02:41:08 AM »
oooooh!
You got to put quotes around the %t% too!

Ah thats why I was messing up. I tried to make it a string by putting quotes on the "two words" but that didnt work

String comparison in Windows command language (batch) is very simple. Everything is evaluated, so the quotes are part of the string and they have to be on both sides of the == section of the statement.

You don't have to use quotes, although many people do, you can use just about any non-special character or characters (so not <>|% etc).


C:\>set var=egg

C:\>if (%var%)==(egg) echo yes
yes

C:\>if [%var%]==[egg] echo yes
yes

C:\>if {%var%}=={egg} echo yes
yes

C:\>if .%var%.==.egg. echo yes
yes

C:\>if $%var%$==$egg$ echo yes
yes

C:\>if abc%var%def==abceggdef echo yes
yes