How to switch command directory dynamically?

Hi guys:
I want to do some common operate both for ipv4 mangle rule and ipv6 mangle rule,
for example:

:local pam "4"
:local ruleCnt 0

:if ($pam = "4") do={
    /ip firewall mangle
} else={
    /ipv6 firewall mangle
}

:set ruleCnt [:len [find]]
# and other code both for ipv4 and ipv6

:log warn $ruleCnt

:log warn "end"

but it seems that this is not work.(there’s a runtime error at the line::set ruleCnt [:len [find]])

Any idea? Thanks.

Some other unsuccessful try:
Define a function to call later after changing “directory”: NO, the function when created remains on “root”
Create a script and call it later after changing “directory”: NO, the script everytime start on “root”


The “change directory” is local only for :if statement

and this is executed on the “root”:

:set ruleCnt [:len [find]]

this line is interpreted as:

:set ruleCnt [:len [:find “string” “what-search-inside-the-string” -1]]

and gives error because the two necessary parameters are not specified.

The solutions may vary for each case, but for the script you provided for example, you need to do like this:

# changed to global to quickly test the script on the terminal
:global pam "4"
:global ruleCnt 0

:if ($pam = "4") do={
    /ip firewall mangle
    :set ruleCnt [:len [find]]
}

:if ($pam = "6") do={
    /ipv6 firewall mangle
    :set ruleCnt [:len [find]]
}

:log info $ruleCnt

:log info "end"

It works for sure:
From a template create a new temporary script where the “directory” is set at the beginning.
For example if the script used for the model contains:

:global ruleCnt
:set ruleCnt [:len [find]]

simply add on top of new temporary script:

/ip firewall mangle
<INSERT MODEL SCRIPT HERE>

Then call the temporary script.

The source can be set like this:

:local iwantusethatdir "/ip firewall mangle"
/system script 
remove [find where name="workingscript"]
add name=workingscript source="$iwantusethatdir\r\n$[get [find where name="script-model"] source]"
run workingscript

@rextended Thank you for your reply.

The “change directory” is local only for :if statement

Yes, like a local variable,you can’t access it out the if block.

# changed to global to quickly test the script on the terminal
:global pam "4"
:global ruleCnt 0

:if ($pam = "4") do={
    /ip firewall mangle
    :set ruleCnt [:len [find]]
}

:if ($pam = "6") do={
    /ipv6 firewall mangle
    :set ruleCnt [:len [find]]
}

:log info $ruleCnt

:log info "end"

yes, it works. but need duplicate the same code both for ipv4 and ipv6.

:local iwantusethatdir "/ip firewall mangle"
/system script 
remove [find where name="workingscript"]
add name=workingscript source="$iwantusethatdir\r\n$[get [find where name="script-model"] source]"
run workingscript

Understand, create the script dynamically, and run it. I think it’s a solution. Thank you.

Hope there will be a simple solution supported by offical.