CD命令无法在FOR循环中运行? [英] CD command not working inside FOR loop?

查看:72
本文介绍了CD命令无法在FOR循环中运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是批编程的新手.

以下程序的输出:

@ECHO OFF
cd /d C:%HOMEPATH%\AppData\Roaming\Mozilla\Firefox\Profiles
echo %cd%
FOR /F %%i IN (temp_list.txt) DO (
 echo i is %%i
 cd folder
 echo %cd%
)
cd folder
echo %cd%
pause

是:

C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles
i is e6slask2.default
C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles
i is random.default
The system cannot find the path specified.
C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles
The system cannot find the path specified.
C:\Users\arnab\AppData\Roaming\Mozilla\Firefox\Profiles\folder
Press any key to continue . . .

我知道 FOR 逻辑是错误的(我实际上在做 cd文件夹两次,只有在文件夹"内没有文件夹"的情况下才应该是可能的))
但是为什么cd文件夹不带我进入"C:\ Users \ abhagaba.ORADEV \ AppData \ Roaming \ Mozilla \ Firefox \ Profiles \ folder" 中的第一次迭代FOR 循环?

I understand that the FOR logic is wrong (i effectively am doing cd folder twice, should be possible only unless there is a 'folder' inside a 'folder')
but why isn't the cd folder taking me to the "C:\Users\abhagaba.ORADEV\AppData\Roaming\Mozilla\Firefox\Profiles\folder" for the first iteration in the FOR loop?

CD 是否不能在 FOR 循环内工作?

Does CD not work inside a FOR loop?

推荐答案

首先,批处理不更新代码块中的变量,但是必须有一种解决方法.这就是使用 for / if 命令后, Setlocal EnableDelayedExpansion 非常有用的原因.代码如下:

First thing first, batch don't update variables inside a code block, but there must be a way to solve it. That's why Setlocal EnableDelayedExpansion is pretty useful once working with for/if commands. The code will look like:

@ECHO OFF
Setlocal EnableDelayedExpansion

cd /d C:%HOMEPATH%\AppData\Roaming\Mozilla\Firefox\Profiles
echo %cd%
FOR /F %%i IN (temp_list.txt) DO (
    echo i is %%i
    cd folder
    echo !cd!
)
cd folder
echo %cd%
pause

用感叹号替换百分号(%var%->!var!)将解决您的问题.不必担心代码块外的变量,使用旧式%var%不会影响结果.

Replace percent signs with exclamation marks (%var% -> !var!) will solve your problem. Don't worry about variables outside the code block, using old-style %var% will not affect the result.

这篇关于CD命令无法在FOR循环中运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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