我在 Windows 7 上有一个 which.bat,
@echo off
REM This bat searches a file in PATH list to see whether a file can be found.
REM If found, it shows the file's full path.
REM which.bat gcc.exe
REM shows
REM gcc.exe is found: D:\GMU\MinGW2\bin\gcc.exe
REM
REM Note: Filename extension is significant in the search. E.g. If you run
REM which.bat gcc
REM gcc.exe will not be matched.
IF "%1" == "" goto END
IF "%~$PATH:1" == "" (
echo %1 is not found in any directories from PATH env-var.
) ELSE (
echo %1 is found: %~$PATH:1
)
:END
在我今天发现一个奇怪的行为之前,这个 bat 一直很好用。
有一个文件O:\temp\pfiles (x86)\mystuff.txt
,PATH有内容:
PATH=O:\temp\pfiles (x86);D:\CmdUtils
运行which mystuff.txt
,我得到了非常奇怪的输出:
\mystuff.txt was unexpected at this time.
经过一番摸索,我发现是目录名中的 (x86)
导致了问题。要解决此问题,我必须向 echo
添加引号,如下所示:
echo %1 is found: "%~$PATH:1"
这种调整的缺点很明显:引号被打印到屏幕上,这在程序员看来并不总是需要的。
任何人都可以帮助解释这种奇怪的行为吗?
我发现这个问题是因为在我的真实环境中,我在 PATH 中有一些路径,如 C:\Program Files (x86)\Common Files\NetSarang
,它们表现出完全相同的症状。
最佳答案
MS Dos 是非常简单的 shell 实现,而且我发现对一个 DOS 命令行的解释分为两个阶段:
- 评估当前行中的变量
- 评估命令行的解释
在这种情况下,您的命令行:
IF "%~$PATH:1" == "" (
echo %1 is not found in any directories from PATH env-var.
) ELSE (
echo %1 is found: %~$PATH:1
)
将被解释为:
IF "O:\temp\pfiles (x86)\mystuff.txt" == "" (
echo mystuff is not found in any directories from PATH env-var.
) ELSE (
echo mystuff.txt is found: O:\temp\pfiles (x86)\mystuff.txt
)
现在我们可以注意到 (x86)
中的问题,即解释器以某种方式看到这个 - 首先 )
关闭 else 语句:
) ELSE (
echo mystuff.txt is found: O:\temp\pfiles (x86
)\mystuff.txt
)
解决方案:将“”放在所有可能有问题的变量周围。
我通常会在整个 echo 命令内容周围加上引号,例如:
echo "%1 is found: %~$PATH:1"
关于Windows .bat 文件,%~$PATH :1 quotes issue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16518297/