0

From https://stackoverflow.com/questions/7005951/batch-file-find-if-substring-is-in-string-not-in-a-file, I figured how to check if PATH variable has a certain substring(groovy's path). However, my PATH variable has spaces in it and that results in error "Files\Amazon was unexpected at this time.".

set str1=%PATH%
rem set str1=C:\lang\groovy-2.4.21\bin
rem set str1=foo
if not x%str1:groovy-2.4.21=%==x%str1% goto noNeedToAddGroovy
echo "Groovy is not in the path. Add groovy to the path"
SET "PATH=C:\lang\groovy-2.4.21\bin;%PATH%;
endlocal

In the above code block, the below line

if not x%str1:groovy-2.4.21=%==x%str1% goto noNeedToAddGroovy

gives the error "Files\Amazon was unexpected at this time".

How can I correctly escape the spaces in the str1 variable ?

anjanbacchu
  • 1,297
  • 6
  • 24
  • 43

1 Answers1

0

You can just add the quotes on both side.

if not x%str1:groovy-2.4.21=%==x%str1% goto noNeedToAddGroovy

becomes

if not "x%str1:groovy-2.4.21=%"=="x%str1%" goto noNeedToAddGroovy

So why does this work?

An IF statement will check everything on the left of == and compare it to everything on the right of ==.

So writing BLA%1BLA==BLAtestBLA will test if %1 is the same as test as the BLA part exists on both sides of the ==.

By using quotes it tests for "xxx"=="yyy" which is the same as xxx==yyy.

But in scripting, everything separated by a space is seen as a parameter. If you put quotes around it, everything inside quotes is seen as one parameter instead.

So yes, it does compare with the quotes on either side, but given that for the comparison that doesn't matter, it works, and the quotes are basically so you don't need to escape strings and make things unnecessarily complex.

LPChip
  • 59,229
  • 10
  • 98
  • 140
  • Thanks. that worked. I tried adding quotes to the whole expression and that didn't work. Could you also explain the why you added quotes wherever you added so that next time I can try fixing myself. – anjanbacchu Mar 11 '22 at 10:14
  • You're welcome. I've edited my answer to add the explaination. – LPChip Mar 11 '22 at 10:53