Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing exclamation marks as parameters in batch subroutine call

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

like image 752
user3142150 Avatar asked Oct 27 '25 14:10

user3142150


1 Answers

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
like image 131
jeb Avatar answered Oct 30 '25 07:10

jeb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!