Building on LeRouteur's answer, the following might be a useful compromise:
@echo off
if "%~1" == "." cd /d F:\mypath && goto :eof
echo F:\mypath
Running just my-path
will echo the path, as it currently does, but running my-path .
(i.e. with a single full-stop as a parameter) will change to that path.
If you dislike having the path entered twice, this can be avoided by using an environment variable, but to do so "cleanly" (without polluting your existing environment) needs a little thought:
@echo off
setlocal
set "MYPATH=F:\mypath"
if "%~1" == "." (
endlocal && cd /d "%MYPATH%"
goto :eof
)
echo "%MYPATH%"
The use of setlocal
means any changes to the environment (e.g. MYPATH
) will only be made locally: running endlocal
or reaching the end of the batch-file will revert to the original environment (see setlocal /?
and endlocal /?
).
Using setlocal
is very common in batch-files so that any environment variables they use/change don't "pollute" the main environment. The problem is that the current directory is part of what is localized: if you run cd
while setlocal
is in effect, you will return to your starting directory when the script exits.
One solution is to put the endlocal
and cd
commands on the same line. The way batch-files are parsed means that the evaluation of MYPATH
happens while the environment is still "local" (so it still has the right value), but the execution of the cd
command (using the value that was obtained in the first pass) doesn't happen until after endlocal
has executed, meaning the directory will be changed when it returns to the command-line.
The way I define MYPATH
, and use its value (enclosed in double-quotes) allows for the path to contain spaces. Perhaps not necessary here, but a good habit to get into when writing batch-files.
As a final option, you could replace cd /d
with pushd
. The latter "pushes" the current directory onto a stack before changing to the new one (see pushd /?
). When you are finished doing whatever you need to do in MYPATH
you can then run popd
to return to whichever directory you originally ran my-path .
from.
cd
command was insidesetlocal
...endlocal
its effect would be lost when the script ends. The first part would be fine: the main reason I did it the way I did was that for a "more substantial" original script, theif
line can be dropped in at the beginning without affecting the rest of the script. Using) else (
...)
as you suggested would nest the rest of the script unnecessarily. [cont]cd F:\mypath
andgoto :eof
on separate lines would be fine, and I did in fact toy with doing it like that.