【问题标题】:Escaping forward slashes : Windows CMD and Bash转义正斜杠:Windows CMD 和 Bash
【发布时间】:2015-08-21 07:36:51
【问题描述】:

我遇到需要从 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 cmd的示例。注册表项?拖放到打开的cmd 窗口中? start "" cmd /C command path?另一个?
  • 我在 windows 中提示输入路径并将输入的值传递给 sh。例如set /p path=Enter script path: 并调用如下: sh -c %path%

标签: windows shell cmd escaping


【解决方案1】:

切勿以所述方式 (set /p path=Enter path) 更改 %path% 环境变量。请改用其他名称(例如set /p _path=Enter path)。 %path% variable has a special meaning in Windows environment 及其正确的值在这里具有至关重要的意义。另见PATH command

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

.bat.cmd文件扩展名保存下面的代码sn-p,例如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%

更多资源(必读):

【讨论】:

  • 路径是一个错字。我的意思是输入_path,就像你所做的那样。无论如何,您的解决方案帮助我解决了这个问题。谢谢。我也接受了解决方案。
【解决方案2】:

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

【讨论】:

  • 我能做到。但是,由于正在提示路径,例如set /p path=Enter path: 然后作为 sh -c %path% 传递,我不能指望用户确实会输入正斜杠。叹息!
  • 你能用正斜杠替换反斜杠吗?在 cmd set p=e:a\b\c (初始设置)中尝试,使用 set p=%p:\=/% 更改并使用 echo "%p%" 进行检查
猜你喜欢
  • 2016-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-29
  • 2015-01-23
  • 1970-01-01
相关资源
最近更新 更多