在宏中设置/ a后的垃圾回波

问题描述 投票:2回答:3

我的自定义宏有问题,还不知道如何解决。我希望这里的人知道答案,在他或她的有用建议下,我的生活会变得更加光明。示例ms-dos脚本:

@echo off
setlocal enabledelayedexpansion

set @test_macro=^
 set /a "test_num1=1"^&set /a "test_num2=1"^&^
 (for /L %%n in (1,1,10) do (set /a "test_num1+=%%n"^&set /a "test_num2*=%%n"))^>nul^&^
 echo ^^^!test_num1^^^! ^^^!test_num2^^^!

set @test_of_test_macro=for /F "usebackq tokens=*" %%i in (`"cmd /d /q /e:on /v:on /r ^!@test_macro^!"`) do echo %%i

echo Usual call, gives expected output "56" ^& "3628800":
%@test_macro%

echo Call from another macro, gives expected output "56" ^& "3628800", but followed by garbage "11":
%@test_of_test_macro%

给出下一个输出:

Usual call, gives expected output "56" & "3628800":
56 3628800
Call from another macro, gives expected output "56" & "3628800", but followed by garbage "11":
1156 3628800

此错误行为随初始化的数字变量的数量及其初始化顺序而变化,但是上面的脚本给出了问题的表示。

有人知道抑制这些错误回显符号的简单可靠方法吗?并非总是可以解决此问题,以某种方式取消它将非常有用。

先谢谢您。

batch-file command-line set echo
3个回答
0
投票

糟糕,问题已解决。在每次初始化数字变量后添加^> NUL就足够了:

set /a "test_num1=1"^&set /a "test_num2=1"^>NUL^&^

它解决了这个问题。谢谢


0
投票

使用嵌套宏总是有点复杂,尤其是当您尝试使用cmd /V:on执行它们时。

处理(扩展)所有扩展阶段而没有看到发生的情况有点棘手。

在您的情况下,echo ^^^!test_num1^^^! ^^^!test_num2^^^!在直接调用@test_macro时效果很好,但是当您使用@test_of_test_macro尝试使用它时,变量将展开[[之前,其余代码甚至开始。通过在启动宏之前设置两个变量来对其进行测试

set test_num1=HELLO set test_num2=WORLD %@test_of_test_macro%
结果输出为11HELLO WORLD

但是使用cmd启动宏不是一个好主意,因为您失去了宏的优势,它们很快!但是,使用cmd.exe启动它们的代价要比单纯调用函数高得多。


0
投票
感谢您的回复,特别是对Mofi的回复:在这种情况下,最好不要使用算术赋值。我修改了示例以使用相反的调用顺序,它对我有用:

@echo off setlocal ENABLEEXTENSIONS enabledelayedexpansion set @test_macro=^ set "test_num1=1"^&set "test_num2=1"^&^ (for /L %%n in (1,1,10) do (set /a "test_num1+=%%n"^&set /a "test_num2*=%%n"))^>nul^&^ echo ^^^!test_num1^^^! ^^^!test_num2^^^!^&^ set "test_num1="^&set "test_num2=" set @test_of_test_macro=for /F "usebackq tokens=*" %%i in (`cmd /d /q /e:on /v:on /r "^!@test_macro^!"`) do echo %%i echo Call from another macro, gives expected output "56" ^& "3628800" (without any "11"): %@test_of_test_macro% echo Usual call, gives expected output "56" ^& "3628800": %@test_macro%

© www.soinside.com 2019 - 2024. All rights reserved.