1

After running the code below, my .bat file closes immediately

@echo off
FOR /F "tokens=*" %%G IN ('dir /b | findstr /r "test.*.apk"') DO set var=%%G
echo %var%
cmd /k

but if i run a slightly modified version without the matching regex it works fine

@echo off
FOR /F "tokens=*" %%G IN ('dir /b /s "test-20190201.apk"') DO set var=%%G
echo %var%
cmd /k

Does anyone know why?

  • Have you seen actual warning/error by running it in cmd.exe? – Mayur Feb 01 '19 at 11:47
  • 2
    What do you mean by "closes immediately"? ***What*** "closes immediately"? The command window? How do you run the script? And please read about [how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as [this question checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Feb 01 '19 at 11:49
  • Other than one is doing a recursive search and the other not, you need to escape the **`|`** in your first example, to prevent it closing due to error. – Compo Feb 01 '19 at 11:55
  • 3
    why don't you `dir /b "test*.apk"`? Or even better `for %%G in (test*.apk) do...`? – Stephan Feb 01 '19 at 11:58

1 Answers1

1

You need to escape the pipe:

@echo off
FOR /F "tokens=*" %%G IN ('dir /b ^| findstr /r "test.*.apk"') DO set var=%%G
echo %var%
cmd /k

Otherwise you'll break the FOR parser because the pipe is executed with higher prio than the FOR

npocmaka
  • 55,367
  • 18
  • 148
  • 187