Fix a batch script to handle closing parentheses inside an if block

霸气de小男生 提交于 2020-01-25 03:10:12

问题


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

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

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.

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

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 %*
)

回答1:


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!
)

Or you could use functions.

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

:php5_exec
php5 %*
exit /b

:php7_exec
php5 %*
exit /b


来源:https://stackoverflow.com/questions/59066703/fix-a-batch-script-to-handle-closing-parentheses-inside-an-if-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!