Saturday, January 21, 2017

windows - CMD: Append to path without duplicating it?


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


Answer



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 containig 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 comments


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...