batch script variable unset in for loop has no effect

断了今生、忘了曾经 提交于 2019-12-02 06:14:15

http://judago.webs.com/variablecatches.htm has an explanation for my problem. The magic lines were setlocal enabledelayedexpansion and calling var as echo !var:~-9!. ! vs % ...wow! cmd still amazes me.

You found the source of your problem, as well as the solution - delayed expansion.

But using FOR while delayed expansion is enabled can cause problems if any of the filenames contain the ! character. The expansion of the for variable %%i will be corrupted if the value contains ! and delayed expansion is enabled. This is not a frequent problem, but it happens.

The solution is to toggle delayed expansion on and off within the loop

@echo off
setlocal disableDelayedExpansion
for /d %%i in (%1\*) do (
  set var=%%i
  setlocal enableDelayedExpansion
  echo !var:~-9!
  endlocal
)

I'm also wondering what you mean by "I am trying to look into folders one level below and pick out only those folders, hence the ~-9 which extracts the last 9 chars from the path". I suspect your are trying to get the name of the child folder, without the leading path information. If that is so, then using the substring operation is not a good solution because the length of folder names varies.

There is a very simple method to get the name of the folder without the leading path info:

for /d %%i in (%1\*) do echo %%~nxi
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!