0

When I run the following , something happens which stops the bat file after running the for loop because it never outputs the "finish ls bat file!" and pause message.

test.bat:

for /r %cd% %%i in (*.bat) do "subtest.bat" %%i
echo "finish ls bat file!"
pause

subtest.bat

echo %~1
Compo
  • 36,585
  • 5
  • 27
  • 39
Hsu Amanda
  • 31
  • 1
  • 1
  • 9
  • 1
    when you execute `batch-files` from a batch file, it effectively starts a new instance and `subtest.bat` is succesfully executed, the problem is, it never returns to the previous instance to execute the rest of the code, therefore we need to use `call` to execute the script in the same instance, so it is a simple change, just add `call` like `for /r "%cd%" %%i in (*.bat) do call "subtest.bat" %%i` – Gerhard May 09 '19 at 09:26
  • thanks for your answer! another question is:is that the same between bat and batch?! I thought the bat is *.bat and batch is *.cmd, was different script! – Hsu Amanda May 09 '19 at 10:25
  • no. a Batch file is just that, a file with batches of commands that performs a function. a Batch file can have both `.bat` of `.cmd` extension, where `.bat` is the older extension used, but still valid. – Gerhard May 09 '19 at 10:31
  • @GerhardBarnard, what do you mean by "new instance"? Just to clarify: running a batch file (from another with or without `call`) does not initialise a new `cmd` instance; only execution control is passed from one batch file to the other; using `call` lets execution control to be passed back to the calling batch file... – aschipfl May 09 '19 at 11:09
  • @aschipfl yes, that is what I mean, I don't mean new instance of cmd, maybe my wording is a bit vague :) – Gerhard May 09 '19 at 11:35

1 Answers1

1

Use call like this:

for /r %cd% %%i in (*.bat) do call "subtest.bat" %%i

Here is a sample batch file (bat1.bat):

@echo off
for /r %cd% %%i in (*.bat) do call "subtest.bat" %%i
echo bar
pause

Calling subtest.bat with these commands:

echo foo

If you run it you get this output:

foo
foo
bar
Press any key to continue . . .

enter image description here

You can get more information about the call command by typing this on the cmd line:

call /?
gil.fernandes
  • 12,978
  • 5
  • 63
  • 76
  • thanks for your answer! it is work for me after testing. do you know where to learn the bat script systematically? – Hsu Amanda May 10 '19 at 05:48
  • @HsuAmanda actually I like this tutorial for learning about windows batch file scripting: http://steve-jansen.github.io/guides/windows-batch-scripting/ – gil.fernandes May 10 '19 at 06:50