问题
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