Soji
Soji

Reputation: 269

Batch - Echo does not display variable in loop

I am doing some experiments to learn how works the batch script.

I have an issue with displaying some text in a loop

Here is my code :

 for  %%j in (C:\Users\*) do (
 SET _test=123456789abcdef0
  SET _result=%_test:~0,5%
 ECHO %_result%          =12345
 )

And the result is : =12345

If I use the following code :

 SET _test=123456789abcdef0
  SET _result=%_test:~0,5%
 ECHO %_result%          =12345

Then the result is 12345 =12345 as expected.

What is wrong with the loop here ?

Upvotes: 1

Views: 261

Answers (1)

npocmaka
npocmaka

Reputation: 57252

You need delayed expansion.

 setlocal enableDelayedExpansion
 for  %%j in (C:\Users\*) do (
 SET _test=123456789abcdef0
  SET _result=!_test:~0,5!
 ECHO !_result!          =12345
 )

Upvotes: 2

Related Questions