1

I want to set PATH for a tool I wrote using a batch file. But I only want to modify it if the path I want to add isn't already contained in that String. I think I get the syntax wrong because I can't get it to work.

@setlocal enableextensions enabledelayedexpansion
@echo off

set MinGWmsys="%CD%\tools\MinGW\msys\1.0\bin;"
set MinGWbin="%CD%\tools\MinGW\bin;"
set SDCCbin="%CD%"\tools\SDCC\bin;"
set lpath="%PATH%"

if not x%lpath:%MinGWmsys%=% == x%lpath% ( 
echo PATH already contained %MinGWmsys%
) else ( 
echo Adding %MinGWmsys% to PATH
setx PATH "%MinGWmsys%;%PATH%"
)

if not x%lpath:%MinGWbin%=% == x%lpath% ( 
echo PATH already contained %MinGWbin% 
) else ( 
echo Adding %MinGWbin% to PATH
setx PATH "%MinGWbin%;%PATH%"
)

if not x%lpath:%SDCCbin%=% == x%lpath% ( 
echo PATH already contained %SDCCbin%
) else ( 
echo Adding %SDCCbin% to PATH
setx PATH "%SDCCbin%;%PATH%"
)

endlocal

Can somebody help me here please?

Terry
  • 989
  • 8
  • 29
Stefan Falk
  • 23,898
  • 50
  • 191
  • 378
  • Consider using `pathman` instead of `setx` as it is specifically designed to manipulate paths and will do most or all of your work for you. – Harry Johnston Jul 15 '14 at 22:42

1 Answers1

1
x%lpath:%MinGWmsys%=%

is parsed as two variables: %lpath:% and %=%, leaving the string inGWmsys as is. Try:

echo x%lpath:%MinGWmsys%=%

and you will see it.

Instead, you should use

if not "!lpath:%MinGWmsys%=!" == "%lpath%" ( 

so that %variable% is interpolated before !another:value=! (adapted from this post). I used quotation marks instead of x because if seems to (mis)interpret =! even before the variables are interpolated.

A second problem is the quotation marks:

set MinGWmsys="%CD%\tools\MinGW\msys\1.0\bin;"

should be

set MinGWmsys=%CD%\tools\MinGW\msys\1.0\bin;

because obviously your path does not contain a string "%CD%\tools\MinGW\msys\1.0\bin;" with quotation marks.

This works:

@setlocal enableextensions enabledelayedexpansion
@echo off

set MinGWmsys=%CD%\tools\MinGW\msys\1.0\bin;
set lpath=%PATH%

if not "!lpath:%MinGWmsys%=!" == "%lpath%" ( 
echo PATH already contained %MinGWmsys%
) else ( 
echo Adding %MinGWmsys% to PATH
setx PATH "%MinGWmsys%;%PATH%"
)

endlocal
Community
  • 1
  • 1
Alexander Gelbukh
  • 2,104
  • 17
  • 29