如何在不更改目录的情况下运行 BAT 脚本?
如何在不更改目录的情况下运行 BAT 脚本?
我在 ./a
中,脚本 cd 到 ./a/bc
中。如果我出于某种原因需要终止我的脚本,我现在处于 bc
而不是 a
。如何运行脚本而不更改文件夹?
另外,我不喜欢它询问我是否要终止我的脚本。我可以禁用它并让它终止吗?
How do I run a BAT script without changing directories?
I am in ./a
and the script cd's into ./a/bc
. If I need to terminate my script for whatever reason I am now in bc
instead of a
. How do I run the script and not have my folder change?
Also, I don't like how it asks me if I'd like to terminate my script. Can I disable that and let it terminate?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
setlocal 命令对此很有用。 setlocal 之后的任何目录更改都只是批处理脚本的本地目录。顺便说一句,这也适用于任何环境变量(set 命令)。
例如,运行此批处理脚本后:
目录将为 c:\temp,因为脚本中的第二个 cd 仅位于脚本本地。
The setlocal command is useful for this. Any directory changes after setlocal are just local to the batch script. BTW this also applies to any environment variables (set commands).
For example, after running this batch script:
the directory will be c:\temp since the second cd in the script is just local to the script.
如果您不需要将环境变量更改传播到当前环境并且无法触及批处理文件(使用
pushd
/popd
变体我通常使用的),您仍然可以生成cmd
的新实例:还有一个很好的特性,即即使被调用的批处理抛出错误,也可以使原始批处理文件保持运行。例如,我在批处理单元测试框架中这样做,以确保失败的批处理文件不会阻止测试的执行。
If you don't need to propagate environment variable changes into the current environment and cannot touch the batch file (to use the
pushd
/popd
variant which I usually use), you can still spawn a new instance ofcmd
:Also has the nice property of leaving your original batch file running even if the called batch throws up errors. I do that in my batch unit testing framework, for example, to ensure that a failing batch file won't stop the tests from executing.
您可以使用
start yourscript.bat
运行脚本。这使得它在新的命令窗口中运行,因此不会影响启动脚本的命令提示符的工作目录。另一种可能性是不使用
cd
而是使用绝对路径。You can run your script with
start yourscript.bat
. This makes it run in a new command window, and therefore does not affect the working directory of the command prompt that started the script.Another possibility is to not use
cd
and use absolute paths instead.第一个问题是:为什么需要改变目录?您可以简单地使用相对于批处理文件之一的路径吗? (例如使用
%~dp0\a\bc
来引用该目录)但是如果您确实非常需要这样做,您可以执行以下操作:
The first question is: why do you need to change the directory? Can you simply work with paths relative to the one of your batch file? (e.g. using
%~dp0\a\bc
to reference the directory)But if you really, really need to do that, you can do the following: