如何“FOR”在cmd批处理文件中工作? [英] How does "FOR" work in cmd batch file?

查看:154
本文介绍了如何“FOR”在cmd批处理文件中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编程了几十种语言20年,但我永远不能理解为什么FOR工作在windows cmd shell批处理文件,无论我多么努力。我阅读

I've been programming in dozens of languages for 20 years but I could never understand how "FOR" work in windows cmd shell batch file, no matter how hard I tried. I read

http:// www .amazon.com / Windows-Administration-Command-Line-Vista / dp / 0470046163 / ref = sr_1_1?ie = UTF8& s = books& qid = 1241362727& sr = 8-1

http://www.ss64.com/nt/for .html

和其他几个在互联网上的文章,但仍然混淆,不能完成任何事情。

and several other articles on the internet but still confuse and cannot accomplish anything.

对于一个更具体的问题,我如何遍历每个路径在%PATH%变量?
我尝试过

For a little more specific question, how can I iterate through each path in %PATH% variable ? I've tried with

rem showpathenv.bat
for /f "delims=;" %%g in ("%PATH%") do echo %%g

第一个路径,不是所有的。为什么?我做错了什么?

That'd show only the first path, not all of them. Why ? What I do wrong ?

推荐答案

没有答案真的有效。我设法自己找到解决方案。
这有点麻烦,但它解决了我的问题:

None of the answers actually work. I've managed to find the solution myself. This is a bit hackish, but it solve the problem for me:

echo off
setlocal enableextensions
setlocal enabledelayedexpansion
set MAX_TRIES=100
set P=%PATH%
for /L %%a in (1, 1, %MAX_TRIES%) do (
  for /F "delims=;" %%g in ("!P!") do (
    echo %%g
    set P=!P:%%g;=!
    if "!P!" == "%%g" goto :eof
  )
)


$ b b

哦!我讨厌批量文件编程!!

Oh ! I hate batch file programming !!

更新

Mark的解决方案更简单,它不会与包含空格的路径一起工作。这是Mark的解决方案的一个小修改版本

Mark's solution is simpler but it won't work with path containing whitespace. This is a little-modified version of Mark's solution

echo off
setlocal enabledelayedexpansion
set NonBlankPath=%PATH: =#%
set TabbedPath=%NonBlankPath:;= %
for %%g in (%TabbedPath%) do (
  set GG=%%g
  echo !GG:#= !
)

这篇关于如何“FOR”在cmd批处理文件中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆