-1
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.

aschipfl
  • 33,626
  • 12
  • 54
  • 99
br0mmie
  • 47
  • 9
  • 1
    there is no `+` operator for the `cd` command; `cd /D %1` is better (though still not perfect due to missing quotation)… – aschipfl Feb 02 '22 at 01:52

4 Answers4

2
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.

Magoo
  • 77,302
  • 8
  • 62
  • 84
1

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.

DT_
  • 36
  • 4
  • Thanks for the clarification but it still doesn't change into the directory ``` mkdir %1 cd %1 ``` – br0mmie Feb 01 '22 at 22:58
  • what error does your file display when run through the command prompt/powershell? – DT_ Feb 02 '22 at 12:28
0

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")
K J
  • 8,045
  • 3
  • 14
  • 36
0

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.

Gerhard
  • 22,678
  • 7
  • 27
  • 43