Similar question to How to keep from duplicating path variable in csh and How to keep from duplicating path variable in ksh. But this time using Windows command line (cmd.exe
).
PATH=C:\path\to\bin;%PATH%
How do I remove duplicates from PATH
? It would like to do this in an automated way: as part of our build process a specific path is added to the environment variable PATH
; when done 20+ times that path is present 20+ times. I want to avoid that.
If you want to avoid adding duplicates to the PATH environment variable inside batch scripts, you could use a subroutine (:label) like e.g.:
:addPath
if not exist "%~1\" exit /b 1
for %%P in ("%PATH:;=";"%") do if /i %%P=="%~1" exit /b 2
set "PATH=%~1;%PATH%"
goto:EOF
then just call this subroutine, passing a folder as argument, like:
call :addPath C:\path\to\bin
call :addPath "C:\path\with space\bin"
Let's see what it does:
exit
for
-loop will iterate over the segments of the PATH variable"%PATH:;=";"%"
)"%~1"
) andexit
the subroutine, there's nothing to do anymore%PATH%
goto:EOF
marks the end of the subroutineTo handle quoting the right way is important, because %PATH%
may contain spaces. When checking the existence of the given argument, I added a backslash to it ("%~1\"
). This will only be true if the argument is a folder (no matter if it already ends with a backslash), otherwise a file would return TRUE, too.
P.S.: Using pure batch will considerably improve performance against calling external processes.