批处理文件中“#"(井号)的用法 [英] Usage of '#' (pound sign) in batch files

查看:618
本文介绍了批处理文件中“#"(井号)的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个批处理文件(portableshell.bat来自 Strawberry Perl 的便携式版本. )使用#,我不明白为什么.我已经在网上搜索过,但似乎没有关于这种用法的参考.我需要模仿批处理文件的功能,但在不了解其确切功能的情况下要谨慎.

I've come across a batch file (portableshell.bat from the portable version of Strawberry Perl) that uses # and I can't understand why. I've searched online but there seems to be no reference to this usage. I need to imitate the batch file's functionality but I'm wary to do so without understanding what it does exactly.

#在这里的目的是什么

set drive=%~dp0
set drivep=%drive%
if #%drive:~-1%# == #\# set drivep=%drive:~0,-1%

在这里:

if not #%1# == ## "%drivep%\perl\bin\perl.exe" %* & goto END

(这是整个文件的 pastebin ,供参考)

(here's a pastebin of the entire file, for reference)

推荐答案

使用#字符可以在比较中正确处理空值/未定义的值,即避免在变量求值时与未定义的值进行比较

The # character is there so that null/undefined values are properly handled in the comparison, namely to avoid comparing to undefined values should the variable evaluate to them.

几乎任何字符都可以达到此目的(只要在此上下文中没有其他含义).常见的选择是[]{}. ""也可以使用.

This purpose can be served by almost any character (as long as it doesn't have another meaning in this context). Common choices are [] and {}. "" can also be used.

根据dbenham的评论,使用除""之外的任何其他内容通常是不好的做法.当变量有自己的引号时,引号可能会失败,但是当扩展变量没有引号时(例如扩展路径),引号是安全的.在所有情况下唯一安全的方法是延迟扩展.

According to dbenham in the comments, using anything other than "" is generally bad practice. Quotes can fail when the variable has its own quotes, but is safe when the expanded variable cannot have them, as when expanding paths. The only way that's safe in all cases is delayed expansion.

此外,没有理由用#[或任何使用的东西包围变量扩展.对于问题的批处理文件,显然只是为了对称.

Also, there is no reason to surround a variable expansion with # or [ or whatever is used. In the case of the batch file of the question, it is apparently just for symmetry.

有关此问题的更多信息,请阅读该问题.

A bit more about this can be read in this question.

感谢 CodeCaster 寻求帮助

Thanks to CodeCaster for the help

这篇关于批处理文件中“#"(井号)的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆