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?

1
  • 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. Commented Jul 15, 2014 at 22:42

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

Do you know how I have to change it to make it work?
Just added how to do it at the end of the solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.