16

For one CMD session I can easily set a new path: SET PATH=%PATH%;"insert custom path here"

Doing so in a batch file does not consider whether the custom path is already included. How do I avoid duplicating it (i.e. check whether it is already contained in the PATH "string").

Remarks:

  1. Related: How do I append user-defined environment variables to the system variable PATH in Windows 7?
  2. Related: How can I permanently append an entry into the system's PATH variable, via command line?
  3. Same question for UNIX: Add directory to $PATH if it's not already there
  4. Some "CMD" String ops explained: http://ss64.com/nt/syntax-replace.html
Horst Walter
  • 2,083

4 Answers4

21

Similar to MaddHackers answer, just more compact.
echo %path%|find /i "%np%">nul || set path=%path%;%np%

%np% is your new path, of course you can use literals instead. What it does: echo %path%|find /i "%np%">nul searches existing path for a string, discarding output. || means execute on failure, so it means: Search path for string to be added, and if not found, add it.

Edit: Generally it's not required to quote paths, even those containing spaces, but if you do want to quote them, this version will work with double quoted paths:
echo %path%|find /i "%np:"=%">nul || set path=%path%;%np%

Edit: changed findstr /i /c: to find /i as findstr may misinterpret some sequences as noted by KubaOber in their comments

u01jmg3
  • 310
wmz
  • 7,358
5

I know it's dirty, but this should work:

 SET PATH=$(echo $PATH | awk -F"%checkstr%" '{ print ($(NF-1) ~ 0) ? $PATH:%newpath% : $PATH; }')

where %checkstr% is the string to check for in the PATH and %newpath% is the new PATH to append to the current PATH

Hope that helps, and I'm sure there's an easier way, but that should do the trick for now.

EDIT

So if you don't want to add the UNIX tools to Windows, you can try this batch syntax:

echo %PATH% | find /C /I "<string to find>" > out.txt 
set /p dne= < out.txt
if 0 EQU %dne% (set PATH=%PATH%;"<custom path>")
del out.txt

Ugh, not any prettier, and can be done as one line if you can get the pipe'ed find command to work as a subcommand in the if statement...

MaddHacker
  • 381
  • 2
  • 8
2

Script based around the answer by "wmz" :

@ECHO off
ECHO java_home=%JAVA_HOME%
SET javapath=%JAVA_HOME%\bin
ECHO %path%|findstr /i /c:"%javapath:"=%">nul || set path=%path%;%javapath%
ECHO Path=%path%
PAUSE
djangofan
  • 2,939
1

Updated answer for 2021:

set is no longer working and we need to use setx (little different syntax):

SET mypath=C:\dev\vendor\sass\1.32.4
ECHO %Path%|findstr /i /c:"%mypath:"=%">nul || setx Path "%Path%";%mypath%