0

I have a set of many batch files which are called from one another. For example.

File1.batch --> CALL file2.bat |--> CALL file3.bat
                               |--> CALL file4.bat --> CALL file5.bat
                               |--> CALL file6.bat

Now there is a common set of instruction that I need to execute multiple times in all the bat files. in other words, I want to create a function and use in all file multiple times..

I think I can create a function like this

:COMMONCODE
  ECHO "these are my common steps %~1"
  EXIT /B 0

But If I have 2 issues....

  1. If put these lines in File1.bat somewhere at the top before calling any other batch file my other batch file are not called. I think it just see EXIT /B 0 and stop there

  2. the %~1 is taking the File1.bat parameter as instead and printing it.

I think batch file is executed line by line... What I'm designing as a function is actually just a label. which if encountered before the main code will be executed as is... But is there a way to define a proper function, which will not be executed until called

ThrowableException
  • 1,168
  • 1
  • 8
  • 29
  • Perhaps the responses in https://stackoverflow.com/q/71791634/2128947 would be of assistance. I prefer my second solution there. – Magoo Apr 08 '22 at 21:55
  • 2
    Put your common code in an individual `COMMONCODE.BAT` file and call it in the same way as the rest of .bat files... In your example you can _not_ execute `:COMMONCODE` _label_ from any file other than File1.bat – Aacini Apr 08 '22 at 23:02
  • @Magoo Sorry I did not understand your solution for my use case. – ThrowableException Apr 13 '22 at 14:44
  • @Aacini as you suggested, I created a different bat file for for my common code and called them from other bat files. – ThrowableException Apr 13 '22 at 14:44
  • 1
    Suppose you created `common.bat` containing the very last code sample under `or, better in message.bat`. You could then use `call common error parameterlist` in your code to execute the code in `common` starting at the label `:error` and with parameters `parameterlist`. The actual code shown there is applicable to OP's question. In your case. you could call `common commoncode` to execute the subfunction `commoncode`. You could add all sorts of code within `common.bat` and for instance simply `call common dirlist c:\mydir` from any batch to run (3 separate lines) `:dirlist dir %1 exit /b0` – Magoo Apr 13 '22 at 15:39

0 Answers0