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.

2
  • %str:~0,val% is a syntax error because the shell expects a number there Commented May 19, 2022 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. Commented May 19, 2022 at 17:06

1 Answer 1

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%%%

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.