mkdir %1
cd %cd% + %1
I am trying to make a batch script by the name of mkcd to make a directory from cmd or powershell and then cd into it.
But so far my code doesn't work. It creates the directory but doesn't change into it.
mkdir %1
cd %cd% + %1
I am trying to make a batch script by the name of mkcd to make a directory from cmd or powershell and then cd into it.
But so far my code doesn't work. It creates the directory but doesn't change into it.
md "%~1"
cd "%~1"
should achieve your goal.
Using "%~1"
first removes, then re-applies quotes to %1
, so a directoryname containing spaces can be assigned.
Append 2>nul
to the md
command to suppress the error message generated should the subdirectory already exist.
You do not need to specify a full path if the folder you want to cd to is in the working directory. Instead just use cd %1
.
Also in batch files, the plus sign does not join strings/arguments.
I tried to be clever and had problems with the way my overly complicated environments were behaving between drives, including it going to the new directory then returning to the parent drive folder so finaly I decided to keep it simples. This works for me!
md "%~1"&cd /d "%~1"
and as suggested in comments by @aschipfl & @lit this should be better
@if not exist "%~1\*" (md "%~1"&cd /d "%~1") else (cd /d "%~1")
One way is to attempt cd
to the directory, if it does not exist then create it and cd
. This way you do not need to use if exist
:
@cd "%~1" 2>nul || (@mkdir "%~1" & @cd "%~1")
For the first cd
we redirect stderr
to nul as 2>nul
because we do not care about the error results if the directory does not exist. We will however still get an error if there is a problem creating the directory, like permission errors.