1

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 %*
)
CJ Dennis
  • 4,226
  • 2
  • 40
  • 69

1 Answers1

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
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Do I still need `setlocal EnableExtensions EnableDelayedExpansion`? I don't really understand what it does except "fixing" things. The first one works without `EnableExtensions`. – CJ Dennis Nov 27 '19 at 10:03
  • @CJDennis `setlocal EnableDelayedExpansion` enables the additional syntax `!variable!` to expand variables, instead of using `%variable%`. The major differences are, the expansion is done at execution time instead of parse time and all special characters are harmless, when using delayed expansion! `EnableExtensions` is nearly always superfluous. – jeb Nov 27 '19 at 10:08