Call one batch script in another batch script and perform operation on the values returned by first script

前端 未结 1 1517
孤独总比滥情好
孤独总比滥情好 2021-01-25 06:09

I have a batch script \"first.bat\" that returns a list of values and an exit code. My task is to call this script in another script \"second.bat\" and perform the operations on

相关标签:
1条回答
  • 2021-01-25 06:38
    @ECHO OFF
    SETLOCAL
    for %%i in (var return1 return2 bat1err) do set "%%i="
    FOR /f %%i IN ('call first') DO SET var=%%i
    FOR /f "tokens=1,2" %%i IN ("%var%") DO set return1=%%i&set return2=%%j
    

    Should set return1 and return2 to your two values BUT the value of ERRORLEVEL generated by FIRST.bat can't be retrieved.

    In your original code, the file t would be generated in any case - and would be zero-length if there was no output from first.bat. I'm confused by your action in only deleting t if no-error-occurs....

    So - what we'd really need to do is to change FIRST.bat a little.

    If first.bat does not use SETLOCAL, then

    set bat1err=%errorlevel%
    

    at an appropriate point would return bat1err set to the errorlevel.

    If first.bat does use SETLOCAL, then life gets a little more complicated

    set bat1err=%errorlevel%
    

    at an appropriate point would set bat1err in the same way, but you would need to use

    ENDLOCAL&set bat1err=%bat1err%
    

    before exiting. This is a parsing trick, cashing in on the way in which the line is first parsed, then executed. What happens is that the line is actually executed as

    endlocal&set bat1err=22
    

    or whatever, setting BAT1ERR within the context of the calling, not the called batch.

    Another way would be to include %errorlevel% in your output, and simply change the analysis to

    FOR /f "tokens=1,2,3" %%i IN ("%var%") DO set bat1err=%%i&return1=%%j&set return2=%%k
    

    OR, depending on quite what the output of first.bat is, you may be able to do it a third way:

    If first.bat produces no output for error but a line of output for success,

    FOR /f %%i IN ('call first') DO SET var=%%i
    if defined var (
     FOR /f "tokens=1,2" %%i IN ("%var%") DO set return1=%%i&set return2=%%j
     ) else (echo Error occurred) 
    

    and again return, return2 and var can be analysed with IF DEFINED to make decisions.

    That really depends on information we don't have.

    0 讨论(0)
提交回复
热议问题