How do I run a BAT script without changing directories?
How开发者_JAVA百科 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?
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:
cd /d c:\temp
setlocal
cd /d c:\windows
the directory will be c:\temp since the second cd in the script is just local to the script.
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 of cmd
:
cmd /c myBatch.cmd arg1 arg2 ...
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.
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.
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:
REM change the current directory pushd ..\a\bc .. do your stuff here REM restore the old "current directory" popd
精彩评论