You are not logged in.

#1 20 Nov 2019 09:33

ontherocks
New Member
Registered: 20 Nov 2019
Posts: 2

Use function parameters in Delayed Expansion

I have a function in a batch file like so

@echo off
setlocal EnableDelayedExpansion

call :myFunc input1

:myFunc
set input=!%~1:str1=str2!
echo !input!

At the line

set input=!%~1:str1=str2!

I want to substitute str1 in input1 with str2. But I am not able to get the syntax right to use %~1 here.
If I use another temporary variable it works, but I do not want to resort to using an extra variable.
Working code

@echo off
setlocal EnableDelayedExpansion

call :myFunc input1

:myFunc
set temp=%~1
set input=!temp:str1=str2!
echo !input!

Offline

#2 22 Nov 2019 13:47

bluesxman
Member
From: UK
Registered: 29 Dec 2006
Posts: 1,129

Re: Use function parameters in Delayed Expansion

You can't perform substitutions in %1 (etc); the only solution is to assign a variable as you have done in your working example.

Last edited by bluesxman (22 Nov 2019 13:47)


cmd | *sh | ruby | chef

Offline

#3 21 Dec 2019 13:22

Aacini
Member
Registered: 05 Dec 2012
Posts: 149

Re: Use function parameters in Delayed Expansion

This works here:

@echo off
setlocal EnableDelayedExpansion

set "input1=This str1 will change"
call :myFunc input1
goto :EOF

:myFunc
set input=!%~1:str1=str2!
echo !input!

Perhaps your problem is a different one?

Antonio

Offline

#4 09 Jun 2020 15:04

ontherocks
New Member
Registered: 20 Nov 2019
Posts: 2

Re: Use function parameters in Delayed Expansion

Aacini wrote:

This works here:

@echo off
setlocal EnableDelayedExpansion

set "input1=This str1 will change"
call :myFunc input1
goto :EOF

:myFunc
set input=!%~1:str1=str2!
echo !input!

Perhaps your problem is a different one?

Antonio

I was using wrong way to pass the value to the function call.  sad
I was using

call :myFunc %input1%

which you have correctly used as

call :myFunc input1

.
If I use percentage sign, I need to use a temp variable inside the function else it doesn't work.

Thanks.

Offline

Board footer

Powered by