0

I am trying to create a .cmd file. In my code, I have a result of a called function. I am able to echo the result, but am not use the result or set it to a new variable?

Here is my code:

@echo off

:get_str
SET /P "str=String: " || SET str=nul
SET len=5
SET pl=false
CALL :pad_str pad_str str len pl
ECHO %pad_str%

ECHO.
GOTO :end

:pad_str <result> <str> <len> <pad_left>
(
    PAUSE>nul | ECHO -- .pad_str --
    SETLOCAL EnableDelayedExpansion
    SET str=!%~2!
    SET len=!%~3!
    SET pl=!%~4!
    CALL :str_len result str
    ECHO !result!
REM      ^^^^^^^^ This is giving me a number as expected.

    SET stl=!result!
    ECHO %stl%
REM      ^^^^^ This is the part that is returning the "ECHO is off." text. 

REM    IF %stl% EQU %len% DO GOTO :end_pad_str     <-- These are killing the program
REM    IF %stl% GTR %len% GOTO :trim_str           <-- because %stl% is empty.
REM    IF %stl% LSS %len% GOTO :sln_less_than_len  <--

    :trim_str
    PAUSE>nul | ECHO -- .trim_str --
    GOTO :end_pad_str

    :sln_less_than_len
    PAUSE>nul | ECHO -- .sln_less_than_len --
    GOTO :end_pad_str

    :end_pad_str
    PAUSE>nul | ECHO -- .end_pad_str --
)
(
    ENDLOCAL
    SET "%~1=%str%"
    EXIT /B
)

:str_len <result> <str>
(
    SETLOCAL EnableDelayedExpansion
    SET str=!%~2!#
    SET len=0
    FOR %%p IN (4096 2048 1024 512 256 128 64 32 16 8 4 2 1) DO (
        IF "!str:~%%p,1!" NEQ "" ( 
            SET /A "len+=%%p"
            SET "str=!str:~%%p!"
        )
    )
)
(
    ENDLOCAL
    SET %~1=%len%
    EXIT /B
)

:end
PAUSE>nul | ECHO -- END --

NOTE: I have also tried:

SET stl=%result%
SET stl=%%result%%
SET stl=!result:~0,-0!
SET stl=%result:~0,-0%`

All of these are equally problematic.

Here is the output when running this:

String: asdfasd
7
ECHO is off.
asdfasd

-- .end --

What is causing this issue and how can I get around it?

ToMakPo
  • 855
  • 7
  • 27
  • you seem to know about delayed expansion. Why don't you use it consequently? `ECHO %stl%` should be `ECHO !stl!`. It's still inside the code block (btw: why a code block here?) – Stephan Nov 19 '17 at 10:56
  • And: `goto` inside a code block will break the code block. – Stephan Nov 19 '17 at 10:57
  • I know they exist but don't know how or when they should be used. For the most part I'm just frankensteining code I see from other examples. I really don't know what I'm doing. – ToMakPo Nov 19 '17 at 12:40
  • see [this question](https://stackoverflow.com/questions/30282784/variables-in-batch-not-behaving-as-expected/30284028#30284028) for a quick view of how delayed expansion works. If you need more stuff to read, follow the linked questions at the right side. Once you got the concept, there will be no more guessing. – Stephan Nov 19 '17 at 14:35

0 Answers0