包含带空格的可执行路径的环境变量是否也应包含必要的引号?
定义环境变量时(对于我来说,在 Windows 上,也许有更通用的准则),
set MY_TOOL=C:\DevTools\bin\mytool.exe
如果该工具位于带空格的路径上,那么
set MY_TOOL=C:\Program Files (x86)\Foobar\bin\mytool.exe
环境变量是否应该已经包含必要的空格?
也就是说,它应该是:
set MY_TOOL="C:\Program Files (x86)\Foobar\bin\mytool.exe"
而不是上面没有空格的版本吗?
注意:根据乔伊的回答,我真的应该将这个问题缩小到我给出的例子。也就是说,环境变量包含一个由用户或另一个批处理脚本调用的单个(可执行/批处理)工具。
也许空间应该以不同的方式转义?
When defining an environment variable (on Windows for me, maybe there is a more general guideline)
set MY_TOOL=C:\DevTools\bin\mytool.exe
if the tool is located on a path with spaces
set MY_TOOL=C:\Program Files (x86)\Foobar\bin\mytool.exe
should the environment variable already contain the necessary spaces?
That is, should it read:
set MY_TOOL="C:\Program Files (x86)\Foobar\bin\mytool.exe"
instead of the above version without spaces?
Note: In light of Joeys answer, I really should narrow this question to the examples I gave. That is, environment variables that contain one single (executable / batch) tool to be invoked by a user or by another batch script.
Maybe the spaces should be escaped differently?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我想说,不要使用引号,并在使用变量的任何地方使用它们:
特别是如果您让用户在某处设置值,我想这是最安全的选择,因为他们通常不会用引号包围它,而不是这样做。
如果有很多地方使用该变量,您当然可以重新定义:
这使事情对您来说更具弹性。或者,您可以检测是否有引号,如果不存在则添加它们以完全确定。
当您的变量仅表示目录的路径并且您想在其中附加文件名时,那么“无引号”的事情就更加重要,否则您将构建类似
或什至的路径:
我怀疑它是否会正确解析。
I'd say, do it without quotes and use them everywhere you use the variable:
Especially if you let the user set the value somewhere I guess this is the safest option, since they usually tend not to surround it with quotes rather than do so.
If there are plenty of places where you use the variable you can of course redefine:
which makes things more resilient for you. Optionally you could detect whether there are quotes or not and add them if not present to be totally sure.
When your variable represents only a path to a directory and you want to append file names there, then the "no quotes" thing is even more important, otherwise you'd be building paths like
or even:
which I doubt will parse correctly.
命令 shell 可以回答您的问题:输入
C:\Pro
并按 Tab 键。自动完成功能将保留所有空格,并在文件名周围添加引号。所以,这就是“官方”所期望的。
(这假设自动完成功能已打开,我不确定默认值是打开还是关闭,但我猜大多数人都打开了它)
The command shell can answer your question: type
C:\Pro
and hit the tab key.Autocomplete will leave all spaces as-is and add quotes around the filename. So, this is what is "officially" expected.
(this assumes that autocomplete is turned on, I'm not sure whether the default is on or off, but most people have it on anyway, I guess)