LoginSignup
5
5

More than 1 year has passed since last update.

Windows batのforをbreakする

Last updated at Posted at 2020-01-01

概要

タイトルそのままbatファイルでのforを途中で切り上げる方法
実際にはbreakとは言えないけども

コード

main.bat
for /l %%i in (0,1,10) do (
  echo %%i
)&if %%i==5 goto :th
:th
output
0
1
2
3
4
5

%%iの値が5になったらgotoでforの外に抜け出す
/l以外に/fでも可能なのは確認済み
抜け出したあとに()が来ても問題ない模様

注意点

bug.bat
for /l %%i in (0,0,1) do (
  命令
)&if "何らかのbreak条件" goto :th
:th

上記のようにforを(do)whileのように扱うと次元の狭間ループから帰ってこれなくなる模様
また、

slow.bat
for /l %%i in (0,1,100000000) do (
  命令
)&if %%i==5 goto :th
:th

のようにforの処理回数が多くなるとループを抜けるのが遅くなる
内部的にはgoto条件を満たした後、for中の命令をスキップして回しているっぽい?

参考

setlocal~endlocalの外に変数をたくさん持ち出す

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5