I tried so many possibilities to achieve this but I keep on getting errors.
I dont know why I can't pass %CD%
and %PATH%
to FINDSTR
.
@echo off
findstr %cd% %path%
echo %errorlevel%
pause
The result is findstr
can't take value from %path%
because it is not a file so I tried to echo
it to file.
@echo off
echo %path% > path.txt
findstr %cd% path.txt
echo %errorlevel%
pause
For now findstr
could open path.txt
but couldn't get the string to compare. The %cd%
didn't appear to work so I tried to put it manually like this:
@echo off
echo %path% > path.txt
findstr c:\foo path.txt
echo %errorlevel%
pause
It works!
So how can I get the current directory value and pass the value to findstr
? or more plainly, how do I detect if the current directory exists within %PATH% variable.
Run the following small example script which uses
FIND
andFINDSTR
with conditionals and also anIF
/ELSE
:So that is three different attempts at the same task, how do they work for you?
There is not any universal, simple, direct way to check if the current folder is included in the
path
variable usingfindstr
because for each referenced folder insidepath
: it can be an absolute or relative reference, it can include or not an ending backslash, it can be or not quoted, it can include or not special characters, it can include (if quoted) semicolons, ...In top of that, in order to use
findstr
to do the check you will need to handle problems with the backslash characters as they are used as escape characters in regular expressions but also in literals when preceding a non alphanumeric character. TrySo, you will need to process each value inside the
path
variable dealing with quoted semicolons, special characters, backslashes, ...Fortunately this was solved by Jeb and dbenham in the 'Pretty print' windows %PATH% variable - how to split on ';' in CMD shell. Using their code to enumerate the elements it the
path
variable, and the approach in the Magoo's answer in this question, we can write somenthing likeFor each element in the path, resolve it to the full qualified path and check against the full qualified path of the current folder.
should do this for most situations but there are exceptions.
path
may contain relative paths (.
or..
) which will not be detected.path
may contain"some;directory"
which will not play nicelyand there is no requirement that the drivename appears in
path
.So - use with caution.