WHERE ignores trailing whitespace in PATH

Microsoft Windows
Post Reply
binki
Posts: 3
Joined: 2022-Oct-27, 4:24 pm

WHERE ignores trailing whitespace in PATH

Post by binki »

So, I accidentally put trailing whitespace in a SET PATH=… command. I was very confused because WHERE would show me the correct location of the executable I had created, but CMD continued to give me a “'«command»' is not recognized as an internal or external command, operable program or batch file.”.

I thought I would experiment more. So I created a folder with a trailing space in its name, placed a script there, and added the path to PATH. When I did this, WHERE could not find the script. But CMD could find and invoke the path correctly.

So, I used to think that I could use WHERE as a debugging utility to determine if CMD would be able to find and execute a command. But now I see that it searches paths differently than CMD does.

It is interesting to note that the “90 byte 'whereis' batch file” at the end of ss64’s page for WHERE operates correctly and follows the same search logic as CMD.

Because I was frustrated by my trailing space and I had trouble googling my issue, I wanted to share this.

My demo script:

Code: Select all

@ECHO OFF
SETLOCAL
ECHO spacey directory with spacey PATH (correctly configured, search should succeed)
MKDIR "\\?\%CD%\tmp-bin " || EXIT /B 1
ECHO @ECHO hello from spacey script!>"tmp-bin \my-spacey-script.cmd"
: # note, the next line must have a trailing space
SET PATH=%PATH%;%CD%\tmp-bin 
WHERE my-spacey-script
CALL my-spacey-script
ECHO 90-byte results:
@for %%e in (%PATHEXT%) do @for %%i in (my-spacey-script%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i
RD /Q /S "\\?\%CD%\tmp-bin "
ECHO done
ENDLOCAL

SETLOCAL
MKDIR tmp-bin || EXIT /B 1
ECHO nonspacey folder but with spacey PATH (incorrectly configured, search should fail)
ECHO @ECHO hello from non-spacey script!>"tmp-bin\my-nonspacey-script.cmd"
: # note, the next line must have a trailing space to display WHERE’s behavior
SET PATH=%PATH%;%CD%\tmp-bin 
WHERE my-nonspacey-script
CALL my-nonspacey-script
ECHO 90-byte results:
@for %%e in (%PATHEXT%) do @for %%i in (my-nonspacey-script%%e) do @if NOT "%%~$PATH:i"=="" echo %%~$PATH:i
RD /Q /S tmp-bin
ECHO done
Script invocation and output:

Code: Select all

C:\Users\binki\Downloads>CALL where-path-script.cmd
spacey directory with spacey PATH (correctly configured, search should succeed)
INFO: Could not find files for the given pattern(s).
hello from spacey script!
90-byte results:
C:\Users\binki\Downloads\tmp-bin \my-spacey-script.cmd
done
nonspacey folder but with spacey PATH (incorrectly configured, search should fail)
C:\Users\binki\Downloads\tmp-bin\my-nonspacey-script.cmd
'my-nonspacey-script' is not recognized as an internal or external command,
operable program or batch file.
90-byte results:
done

Post Reply