Passing exclamation marks as parameters in batch subroutine call

2.2k Views Asked by At

Thanks to this community I have finally learned how to escape exlamation marks for immediate use in a batch delayedExpansion block. (use two escape carets not just one, awesome)

But I can't seem to find or figure out how to pass the contents of a variable containing an exclamation mark as parameter to a batch subroutine.

example:

@echo off
setLocal EnableDelayedExpansion
set variable=Hello^^!
echo "!variable!"
call :subroutine "!variable:^^!=^^!!"
pause
exit

:subroutine
echo "%~1"
exit/b

Output:

"Hello!"
"Hello"
Press any key to continue . . .

I want the second "Hello" to include an exclamation mark. I have tried various permutations of substring replacement on line 5 to no avail.

help

2

There are 2 best solutions below

0
On

You need a different way for the variable replacing, and much more carets.

@echo off
setLocal EnableDelayedExpansion
set variable=Hello^^!
echo "!variable!"
call :subroutine %variable:!=^^^^^^^^^^!%
exit /b

:subroutine
echo %~1
exit /b

Or with quotes: call :subroutine "%variable:!=^^^!%"

In your function you need to expand %1 without any quotes, as the number of carets are always odd in a CALL parameter.

But at all it's a bad idea to try such things.
I agree with Aacini, that you should use pass by reference instead.
This is the only way to handle any possible content.

@echo off
setLocal EnableDelayedExpansion
set variable=Hello^^!
echo "!variable!"
call :subroutine variable
exit /b

:subroutine
echo !%1!
exit /b
0
On

Maybe the problem is not how to pass the data to the subroutine, but how to get the data inside it

@echo off

    setlocal enabledelayedexpansion

    set "var=Hello^!"

    setlocal disabledelayedexpansion
    echo %var%
    call :echo1 %var%
    call :echo2 var
    endlocal

    setlocal enabledelayedexpansion
    echo !var!
    call :echo1 !var!
    call :echo2 var
    endlocal

    endlocal
    exit /b

:echo1
    setlocal disabledelayedexpansion
    echo %~1
    endlocal
    goto :eof

:echo2
    setlocal enabledelayedexpansion
    echo !%~1!
    endlocal
    goto :eof