Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not get a substring of a delayed expansion variable in an if statement?

Why does string-manipulation work inline in an if statement without using delayed expansion variables - but fails otherwise. For example:

set test=testString
if %test:~0,4%==test echo Success

This works correctly; returning Success. However if I do the following:

setLocal enableDelayedExpansion
set test=testString
if !test:~0,4!==test echo Success

I receive the error - 4!==test was unexpected at this time.

Obviously you can get around this by doing something like set comp=!test:~0,4! then just using the !comp! variable in the if statement.

like image 891
unclemeat Avatar asked Dec 02 '13 22:12

unclemeat


People also ask

How do I enable delayed variable expansion?

When cmd.exe is started, delayed variable expansion is enabled or disabled by giving either the /v:on or /v:off option. In a batch file, delayed variable expansion can be enabled with setlocal enableDelayedExpansion .

What is delayed environment variable expansion?

Delayed environment variable expansion allows you to use a different character (the exclamation mark) to expand environment variables at execution time.

How to set environment variable through batch file?

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set. If you call a variable value from a batch file, enclose the value with percent signs (%).

What is EnableDelayedExpansion batch?

Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time, this option is turned on with the SETLOCAL EnableDelayedExpansion command. Variable expansion means replacing a variable (e.g. %windir%) with its value C:\WINDOWS.


1 Answers

npocmaka correctly diagnosed the problem that the IF command gets its own special parsing phase, and token delimiters within the variable expansion are causing problems.

Substitution also causes a problem:

:: This fails
if !test:String=!==test echo Success

The reason why normal expansion works is because that occurs before the IF parsing, but delayed expansion occurs after IF parsing.

An alternative to using quotes is to escape the problem characters.

:: Both of these work
if !test:~0^,4!==test echo Success
if !test:String^=!==test echo Success
like image 53
dbenham Avatar answered Sep 30 '22 08:09

dbenham