修复批处理脚本以处理if块内的右括号 [英] Fix a batch script to handle closing parentheses inside an if block

查看:93
本文介绍了修复批处理脚本以处理if块内的右括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个批处理脚本,可以在不同的环境下运行不同的PHP版本.

I have a batch script to run different PHP versions under different environments.

@ECHO OFF
setlocal EnableExtensions EnableDelayedExpansion
IF "%ANSICON%" == "" (
  php7 %*
) ELSE (
  php5 %*
)

问题在于,它与IF "%ANSICON%" == "" (中的左括号匹配时,在第一个未转义的右括号上断开了.

The problem is it breaks on the first unescaped closing parenthesis as it matches the opening parenthesis in IF "%ANSICON%" == "" (.

C:\>php -r echo'()';
' was unexpected at this time.

C:\>php -r echo'(())';
)' was unexpected at this time.

基于我阅读的其他问题,setlocal EnableExtensions EnableDelayedExpansion行是新的,但它根本没有改变行为.

The line setlocal EnableExtensions EnableDelayedExpansion is new based on other questions I read, but it hasn't changed the behaviour at all.

如何将所有%*都传递给PHP,而不必先进行批处理?

How can I pass all of %* to PHP without it being interpreted by batch first?

此批处理文件表现出相同的行为:

This batch file exhibits the same behaviour:

@ECHO OFF
setlocal EnableExtensions EnableDelayedExpansion
IF "%ANSICON%" == "" (
  echo %*
) ELSE (
  echo %*
)

推荐答案

您可以使用扩展延迟的临时变量,然后括号不会引起问题.

You could use a temporary variable with delayed expansion, then the parentheses don't cause problems.

@ECHO OFF
setlocal EnableDelayedExpansion
set "args=%*"
IF "%ANSICON%" == "" (
  php7 !args!
) ELSE (
  php5 !args!
)

或者您可以使用函数.

@ECHO OFF
IF "%ANSICON%" == "" (
  goto :php7_exec
) ELSE (
  goto :php5_exec
)
exit /b

:php5_exec
php5 %*
exit /b

:php7_exec
php5 %*
exit /b

这篇关于修复批处理脚本以处理if块内的右括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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