0

I want to write a script that opens a cmd, makes cd to some directory, and writes down this directory in this cmd.

So, I tried the following:

start cmd /k cd c:\ && echo %cd%

I was expecting to get "c:\" written in the new cmd that just opened, but it doesn't happen. Instead, echo is done in the caller cmd rather than in the callee.

What should I do?

BTW, I thought maybe parentheses could help, but they don't...

Thanks a lot :)

Squashman
  • 13,649
  • 5
  • 27
  • 36
Dudi Frid
  • 152
  • 7
  • 2
    Possible duplicate of [Best batch practice to run a second command with &&](https://stackoverflow.com/questions/48458062/best-batch-practice-to-run-a-second-command-with) – phuclv Feb 07 '18 at 17:24
  • 2
    `start cmd /V /K cd /D c:\ ^&^& echo !cd!` or `start "" cmd /V /K "cd /D c:\ && echo !cd!"` – JosefZ Feb 07 '18 at 17:27
  • @LưuVĩnhPhúc, their answer doesn't apply for me: I tried start cmd /k "cd c:\ && echo %cd%", and I got the same as if I were not using the quote signs – Dudi Frid Feb 07 '18 at 18:08
  • `start "" /d "c:\" cmd /v /k "echo !cd!"` – Stephan Feb 07 '18 at 18:12
  • @JosefZ, this works:) – Dudi Frid Feb 07 '18 at 19:27
  • @DudiFrid because you haven't used [delayed expansion](https://stackoverflow.com/q/10558316/995714), hence the value of %cd% is the current working directory. Use `start cmd /k /v:on "cd c:\ && echo !cd!"` – phuclv Feb 08 '18 at 02:22
  • 2
    without delayed expansion: `start /d "c:\" cmd /k echo ^%cd^%"` – Stephan Feb 08 '18 at 07:51

1 Answers1

0

You can run

start cmd /k "cd c:\ && echo %cd%"

but in this case %cd% is evaluated when your "start" command is executed. So it is echoed inside the callee CMD, but the value is still the one from caller CMD.

If you want to print the current directory inside the callee CMD, and don't want to use the environment variable that was set in the caller environment, just use the CD command instead of the %cd% environment variable:

start cmd /k "cd c:\ && cd"

If you now want to enter a command in the opened callee cmd, you can again use the %cd% environment variable inside your callee CMD, but you can't use it from outside.

Christoph Bimminger
  • 1,006
  • 7
  • 25