Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Command: how do I push current directory using chdir for popping later?

Context/Objective:

In windows 7, I'm developing a batch script using regular windows commands. Within this batch, I need to save the current directory first thing so it can be restored when the script finishes running.

What I have tried so for:

I've attempted to use commands of chdir, pushd and popd to make it work.

  • Try 1:

    PUSHD CHDIR

    REM main script body

    POPD

    Result: error on PUSHD line "the system cannot find the path specified"

  • Try 2:

    SET curdir=CHDIR

    PUSHD %curdir%

    REM main script body

    POPD

    Result: same error on PUSHD line "the system cannot find the path specified"

  • Other tries: Also googling didn't yield any satisfactory results.

The Questions:

Can I make it work using these commands? Or is there another set of commands that I need to use?

Note:I'm looking for a solution using windows native commands only, third party tools or powershell is not an option.

like image 570
Leo Nix Avatar asked Dec 11 '15 15:12

Leo Nix


2 Answers

You can use . to represent the current diretory.

Try this:

PUSHD .

REM The rest of you script

POPD
like image 107
aphoria Avatar answered Sep 28 '22 06:09

aphoria


Your problem is that you need to use the CD command (instead of CHDIR) and don't forget to wrap it in %'s.. It is common to think they are they same, but they do differ, slightly, in this way.

Try the following example in a batch file:

@echo off

echo Initial directory set to:
cd "%UserProfile%\Desktop"
echo   `%cd%`
echo.

pushd %CD%

echo Changing to %AppData%
REM main script body
cd /D %AppData%
echo   `%cd%`
echo.

echo Changing to %LocalAppData%
cd /D %LocalAppData%
echo   `%cd%`
echo.

echo.
echo About to POPD
pause
POPD
echo   `%cd%`
echo.

I should note the @aphoria's answer is just as valid.

like image 43
kodybrown Avatar answered Sep 28 '22 05:09

kodybrown