开发者

variable in variable in batch and delayed expansion

开发者 https://www.devze.com 2023-01-02 19:03 出处:网络
I\'m trying to use variable in variable in conjunction with delayed expansion but still no luck. SETLOCAL EnableDelayedExpansion

I'm trying to use variable in variable in conjunction with delayed expansion but still no luck.

SETLOCAL EnableDelayedExpansion
SET ERROR_COMMAND=exit /B ^!ERRORLEVEL^!

This is my last try. I want to setup an ERROR_COMMAND to be called when one of the steps in batch file crashes. The command is supposed to be:

IF ERRORLEVEL 1 !ERROR_COMMAND!

or

IF ERRORLEVEL 1 %ERROR_COMMAND%

The thing is, I'm not able to find out, how to SET properly the ERROR_COMMAND variable, so that ERRORLEVEL is not evaluated at the time of assignment, but at the time of evaluating the variable

Of course I can copy&paste 开发者_运维技巧the code all over the batch file, but using the variable just seems a bit prettier...

Anyone?

Thanks, Milan


I'm sure there are many ways to do this, here are two:

A)

SET ERROR_COMMAND=call echo.errlvl=%%ERRORLEVEL%%

verify failthis 2>nul
%ERROR_COMMAND%

B)

setlocal DISABLEDELAYEDEXPANSION&set "X=!"
call (endlocal&set "ERROR_COMMAND=echo.errlvl=%X%ERRORLEVEL%X%")&setlocal ENABLEDELAYEDEXPANSION

verify failthis 2>nul
%ERROR_COMMAND%

It should also be noted that if someone does set ERRORLEVEL=foo (In your script or "globally"), %ERRORLEVEL% will not resolve correctly (Same goes for %CD% and all the other built in special variables)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号