Windows Shell 脚本:检查包含双引号的批处理选项
尊敬的专家们,您好!
我想在我的批处理脚本中检查参数(或参数)字符串是否存在:
if "%*"=="" findstr "^::" "%~f0"&goto :eof
如果没有任何参数包含在双引号中,则效果很好。例如:
test.bat par1 par2 ... --- works
但
test.bat "par 1" par2 ... --- fails
我的问题是:
1)有什么方法可以克服这个问题,而不是要求使用非双引号符号来指定“长”参数,然后使用字符串替换?
2)我可以使用“if”来比较两个同时包含双引号和空格的字符串吗?
非常感谢您及时、明确的答复。
Greetings, dear Experts!
I want to check the existense of parameter (or argument) sting at all in my batch script:
if "%*"=="" findstr "^::" "%~f0"&goto :eof
This works fine if none of parameters is enclosed in double quotes. For example:
test.bat par1 par2 ... --- works
but
test.bat "par 1" par2 ... --- fails
My question are:
1) Is there any way to overcome this instead of requirement for use to use non-double-quoted symbol to specify "long" arguments and then use string substitution?
2) Can I ever use "if" to compare two strings containing both double quotes and spaces?
Your prompt and clear reply would be very much appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
~ 将去掉双引号,但对 %* 不起作用,但如果您只想知道是否没有参数,只需检查 %1 就足够了
您可能需要先调用 setlocal ENABLEEXTENSIONS 以确保扩展已打开(需要~)
~ will strip the double quotes, but does not work on %*, but if you just want to know if there are no parameters, just checking %1 should be enough
You might want to call setlocal ENABLEEXTENSIONS first to make sure extensions are on (required for ~)
谢谢你,安德烈斯。
这里还有两段代码来检查传递参数的存在性和数量:
这里变量 N 包含所需的参数数量。
希望这对某人有帮助!
Thank you, Andres.
Here are two more pieces of code to check the existence and number of passed parameters:
Here variable N contains needed number of parameters.
Hope this helps for somebody!
由于 Andrey 的答案无法正确计算参数,因此即使有超过 9 个参数,这里也有一种可行的方法(它甚至保留了原始参数,因此
%1
仍然通过移动来指向第一个参数)转移
到子例程中):Since Andrey's answer fails to correctly count arguments, here is a way that does work, even with more than 9 arguments (and it even perserves the original ones, so
%1
still points to the first one by moving theshift
ing into a subroutine):