转义正斜杠:Windows CMD 和 Bash

Escaping forward slashes : Windows CMD and Bash

我有一种情况需要从 windows CMD 文件调用 UNIX Shell。调用如下:

sh -c 路径/script.sh

我遇到的挑战是路径作为参数传递给 windows cmd,并包含反斜杠 () 来分隔路径。所以像这样执行命令:

sh -c e:\scriptpath\test.sh 失败,因为 sh 正确报告:e:scriptpathtest.sh 不存在。

用 \ 转义 \ 有效:例如sh -c e:\\scriptpath\\test.sh 会起作用。

问题是:如何在 windows cmd 文件中的输入路径参数中包含 \?例如如果路径输入为 e:\scriptpath,它会自动转换为 e:\\scriptpath?

Windows 还支持目录之间的正斜杠。
尝试 sh -c e:/scriptpath/test.sh

从不 以描述的方式更改 %path% 环境变量 (set /p path=Enter path)。请改用其他名称(例如 set /p _path=Enter path)。 %path% variable has a special meaning in Windows environment and its proper value has vital importance here. See also PATH command.

任何用户输入都应在使用前彻底检查,例如

使用 .bat.cmd 文件扩展名保存以下代码片段,例如32134824.cmd:

@ECHO OFF
SETLOCAL EnableExtensions
:UserInput
rem empty the `_path` variable
set "_path="
rem or set a default value for it as follows:
set "_path=e:\scriptpath\test.sh"
rem prompt for user input
set /p "_path=Enter path [default=%_path%]:"
rem treat the case `set "_path="` and the user pressed only ˙Enter˙
if not defined _path echo wrong path & goto :UserInput
rem or set a default value instead: if not defined _path set "_path=%CD%\test.sh"

rem check if the file exists:
if not exist "%_path%" echo %_path%: file does not exist & goto :UserInput

rem translate to Unix filename conventions
set "_path=%_path:\=/%"
rem or set "_path=%_path:\=\%"

rem next `sh` command is merely echoed for debugging purposes
echo sh -c %_path%

更多资源(必读):