转义正斜杠:Windows CMD和Bash

时间:2015-08-21 07:36:51

标签: windows shell cmd escaping

我遇到需要从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?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

从不以所述方式更改%path%环境变量(set /p path=Enter path)。请改用其他名称(例如set /p _path=Enter path)。 %path% variable has a special meaning in Windows environment及其正确值在此处具有至关重要。另请参阅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%

更多资源(必读):

相关问题