Call a subroutine in a batch from another batch file

前端 未结 4 1524
太阳男子
太阳男子 2020-12-06 13:46

file1.bat:

@echo off
 :Test
echo in file one
call file2.bat (Here i want to call only Demo routine in the file2.bat)

file2.bat:

<         


        
4条回答
  •  青春惊慌失措
    2020-12-06 14:13

    What about providing the target label as the first agrument of the called script? You needed to modify the called dscript then though.

    file1.bat (main):

    @echo off
    echo/
    echo File "%~0":  call "file2.bat" [no arguments]
    call "file2.bat"
    echo/
    echo File "%~0":  call "file2.bat" :DEMO
    call "file2.bat" :DEMO
    echo/
    echo File "%~0":  call "file2.bat" :DEMO A B C
    call "file2.bat" :DEMO A B C
    

    file2.bat (sub):

    @echo off
    set "ARG1=%~1" & if not defined ARG1 goto :TEST
    if "%ARG1:~,1%"==":" goto %ARG1%
    
    :TEST
    echo File "%~nx0", :TEST; arguments: %*
    goto :EOF
    
    :DEMO
    echo File "%~nx0", :DEMO; arguments: %*
    echo   before `shift /1`:
    echo     "%%~0" refers to "%~0"
    echo     "%%~1" refers to "%~1"
    shift /1
    echo   after  `shift /1`:
    echo     "%%~0" refers to "%~0"
    echo     "%%~1" refers to "%~1"
    goto :EOF
    

    Output:

    >>> file1.bat
    
    File "file1.bat":  call "file2.bat" [no arguments]
    File "file2.bat", :TEST; arguments:
    
    File "file1.bat":  call "file2.bat" :DEMO
    File "file2.bat", :DEMO; arguments: :DEMO
      before `shift /1`:
        "%~0" refers to "file2.bat"
        "%~1" refers to ":DEMO"
      after  `shift /1`:
        "%~0" refers to "file2.bat"
        "%~1" refers to ""
    
    File "file1.bat":  call "file2.bat" :DEMO A B C
    File "file2.bat", :DEMO; arguments: :DEMO A B C
      before `shift /1`:
        "%~0" refers to "file2.bat"
        "%~1" refers to ":DEMO"
      after  `shift /1`:
        "%~0" refers to "file2.bat"
        "%~1" refers to "A"
    

提交回复
热议问题