SETLOCAL ENABLEDELAYEDEXPANSION导致CD和PUSHD无法持久保存 [英] SETLOCAL ENABLEDELAYEDEXPANSION causes CD and PUSHD to not persist

查看:153
本文介绍了SETLOCAL ENABLEDELAYEDEXPANSION导致CD和PUSHD无法持久保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在批处理脚本中一起使用setlocal enabledelayedexpansioncd,该脚本似乎无法将更改持久化回shell.

I am trying to use setlocal enabledelayedexpansion and cd together in a batch script, which seems to not persist changes back to shell.

我需要setlocal enabledelayedexpansion的原因是我需要在脚本运行时动态扩展脚本中的变量.

The reason I need setlocal enabledelayedexpansion is that I need the variables in the script to be expanded dynamically upon runtime of the script.

考虑以下 sample 批处理文件:

a.bat
================================
setlocal enabledelayedexpansion
cd ..

上述批处理文件未按预期迁移到先前的目录!

The above batch file does not migrate to previous directory as expected !

检查.

推荐答案

问题是setlocal导致任何当前目录更改在批处理文件中都是本地的.

The problem is that setlocal causes any current directory changes to be local to the batch file.

请参见setlocal /?:

开始在批处理文件中本地化环境更改. 环境 发出SETLOCAL之后所做的更改在批处理文件中是本地的. 必须发出ENDLOCAL才能恢复以前的设置.何时结束 达到批处理脚本的数量,则对任何脚本执行隐式ENDLOCAL 该批处理脚本发出的未完成的SETLOCAL命令.

Begins localization of environment changes in a batch file. Environment changes made after SETLOCAL has been issued are local to the batch file. ENDLOCAL must be issued to restore the previous settings. When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

当前目录包含在环境更改"中.

Current directory is included in "environment changes".

尝试此操作,请注意它在批处理中为C:\回显C:\,但是当该批处理退出时,当前目录仍会重置.

Try this, notice that it echoes C:\ for %CD% inside the batch, but the current directory is still reset when the batch exits.

[11:42:00.17] C:\temp
> cat test.bat
@echo off
setlocal enabledelayedexpansion
cd ..
echo %CD%
[11:42:19.38] C:\temp
> test.bat
C:\

[11:42:23.00] C:\temp
>

这篇关于SETLOCAL ENABLEDELAYEDEXPANSION导致CD和PUSHD无法持久保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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