如何创建这个非常小的 Shell 脚本的 Windows 等价物?

How do I create the Windows Equivalent of This Very Small Shell Script?

我试图在 .bat 文件中实现以下目标。它在设置路径后执行第一个参数之后的所有参数。

# Add your local node_modules bin to the path for this command
export PATH="./node_modules/.bin:$PATH"

# execute the rest of the command
exec "$@"

我已经掌握了第一部分(我认为),但不知道如何进行第二部分,而且在谷歌搜索解决方案时也没有成功。

REM Add your local node_modules bin to the path for this command
SET PATH=.\node_modules\.bin;%PATH%

第一个命令行可以是:

@set "PATH=%~dp0node_modules\.bin;%PATH%"

此命令行添加到 local PATH 环境变量开始的子目录 .bin 的路径 node_modules in [=61] =]批处理文件的目录而不是当前目录

%~dp0 始终扩展到以反斜杠结尾的批处理文件目录路径。出于这个原因,%~dp0 应该始终与 folder/file 名称连接,而无需像此处那样使用额外的反斜杠。

可以用%CD%\代替%~dp0当前目录的子目录node_modules中添加子目录.bin的路径local PATH 环境变量。但请注意,当前目录 可能总是与 批处理文件目录 不同,因此在这里很可能不好。

%CD% 扩展为不以反斜杠结尾的目录路径字符串,除了 当前目录 是驱动器的根目录,在这种情况下 %CD% 扩展为驱动器号 + 冒号 + 反斜杠。因此 %CD% 的用法需要命令行:

@if not "%CD:~-1%" == "\" (set "PATH=%CD%\node_modules\.bin;%PATH%") else set "PATH=%CD%node_modules\.bin;%PATH%"

第二个命令行可以是:

@%*

这个非常短的命令行导致解释所有传递给批处理文件的参数,参数 0 除外作为命令行在解析后由 Windows 命令处理器执行。另见:How does the Windows Command Interpreter (CMD.EXE) parse scripts?

命令行开头的

@ 导致 Windows 命令处理器 cmd.exe 处理批处理文件在解析后不输出命令行。带有命令 set 和带有 %* 的命令行不再需要 @ 在批处理文件顶部带有 @echo off 的行的开头。

@echo off
set "PATH=%~dp0node_modules\.bin;%PATH%"
%*

打开 command prompt、运行 call /? 并阅读解释如何在批处理文件中引用批处理文件参数的输出帮助。

另请参阅 SS64.com,其中包含 Windows CMD 和 Linux Shell 命令的参考。