1

I'm afraid many would find this to be a dumb question...

@ECHO off
SET str=HelloWorld
ECHO.%str%
SET str=%str:~0,5%
ECHO %str%

The output is as expected:

HelloWorld
Hello

But this code below ...

@ECHO off
SET str=HelloWorld
ECHO.%str%
SET /A val=5
SET str=%str:~0,val%
ECHO.%str%

I'm intuitively expecting the same result but its output is strange to me.

HelloWorld
str:~0,val  

Would anyone care to share why and how this can be fixed?

Thank you.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
bnalla
  • 15
  • 4
  • `%str:~0,val%` is a syntax error because the shell expects a number there – phuclv May 19 '22 at 15:59
  • Thank you @phuclv for your time. Yes, you are right about that error I called out. user2956477's contribution below is both helpful and informative. – bnalla May 19 '22 at 17:06

1 Answers1

1

You have to use callcommand which cause doubled set command execution. Variable %val% will evaluate in first set runtime which caused there will be a number in second runtime. Percent signs have to be doubled in this way call SET str=%%str:~0,%val%%%

user2956477
  • 1,208
  • 9
  • 17
  • Wow! Thank you @user2956477! You not only gave the fix but you VERY thoroughly explained it in very few words. Frankly, I didn't know about codes in scripts being evaluated in multiple runtimes and having the need to use 'call' for purposes like this. I learned something great today from you. I sincerely appreciate your time – bnalla May 19 '22 at 17:16