문제

I want to append %MYSQL_HOME%\bin and %CATALINA_HOME%\bin to the Path system environment variable on Windows, but I want to append these only if they are not already appended. How do I do it on the command prompt or in a batch script?

도움이 되었습니까?

해결책

Here's another solution:

path|find /i "%MYSQL_HOME%\bin"    >nul || set path=%path%;%MYSQL_HOME%\bin
path|find /i "%CATALINA_HOME%\bin" >nul || set path=%path%;%CATALINA_HOME%\bin

다른 팁

@ECHO OFF
SETLOCAL
FOR %%a IN (skipsql skipcat) DO SET "%%a="
FOR /f "delims=" %%a IN ('"echo %path:;=&ECHO(%"') DO (
IF /i "%%a"=="%MYSQL_HOME%\bin" SET skipsql=Y
IF /i "%%a"=="%CATALINA_HOME%\bin" SET skipcat=Y
)
IF NOT DEFINED skipsql SET "path=%path%;%MYSQL_HOME%\bin"
IF NOT DEFINED skipcat SET "path=%path%;%CATALINA_HOME%\bin"
ECHO new path=%path%
GOTO :EOF

This should work for you. Remember that it will only work for the current instance of cmd - it's not transmitted to existing or future cmd instances.

@echo off
setlocal EnableDelayedExpansion

for %%a in ("%MYSQL_HOME%\bin" "%CATALINA_HOME%\bin") do (
   if "!path:%%~a=!" equ "!path!" set "path=!path!;%%a"
)

ECHO New path=%path%

Here's a convoluted approach using a temp file:

set PATH_BACKUP=%PATH%
path | findstr "%MYSQL_HOME%\bin" > _tmp.txt
path=%PATH%;%MYSQL_HOME%\bin
for /f %%i in (_tmp.txt) do path=%PATH_BACKUP%
del _tmp.txt

set PATH_BACKUP=%PATH%
path | findstr "%CATALINA_HOME%\bin" > _tmp.txt
path=%PATH%;%CATALINA_HOME%\bin
for /f %%i in (_tmp.txt) do path=%PATH_BACKUP%
del _tmp.txt

Replace _tmp.txt with some other throw-away filename if need be.

This is for a batch file. If using from the command line, replace %%i with %i.

Path consists of two parts, system path and user path. To add directory to user path, first get user path and system path separately. Then use "set" and "setx" commands for setting the path. "set" command sets the environment locally and "setx" globally. At end you can combine the user path and system path back to use the path locally.

for /F "skip=2 tokens=1,2*" %%N in ('%SystemRoot%\System32\reg.exe query "HKCU\Environment" /v "Path" 2^>nul') do if /I "%%N" == "Path" call set "UserPath=%%P"
for /F "skip=2 tokens=1,2*" %%N in ('%SystemRoot%\System32\reg.exe query "HKLM\System\CurrentControlSet\Control\Session Manager\Environment" /v "Path" 2^>nul') do if /I "%%N" == "Path" call set "SystemPath=%%P"
echo ;%UserPath%; | find /i ";%DirToAppend%;" > nul || setx Path "%DirToAppend%;%UserPath%"
echo ;%UserPath%; | find /i ";%DirToAppend%;" > nul || set UserPath=%DirToAppend%;%UserPath%
echo ;%UserPath%; | find /i ";%Dir2ToAppend%;" > nul || setx Path "%Dir2ToAppend%;%UserPath%"
echo ;%UserPath%; | find /i ";%Dir2ToAppend%;" > nul || set UserPath=%Dir2ToAppend%;%UserPath%
set Path=%SystemPath%;%UserPath%
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top