batch-file

How to return to the original directory after invoking change directory in Windows batch?


I want to create a batch file, batch.bat, that accepts two mandatory arguments:

Assume the current directory is father\me\.

User can use this batch as follows:

The job description of batch.bat is as follows.

  1. Moves to %1 directory,
  2. Iterates all *.tex file in the %1 directory.
  3. Save the result in the directory before moving.

The following is the incomplete code:

rem batch.bat takes two arguments.
cd %1
dir /b *.tex > <original directory>\%2.txt

How to return to the original directory after invoking change directory in Windows batch?


Solution

  • If you want to RETURN to original directory, do the first change with PUSHD and return with POPD. That is, moves to %1 directory must be achieved with

    PUSHD %1
    

    instead of CD %1, and the return is achieved with

    POPD
    

    instead of CD where?

    If you want to ACCESS the original directory after changed it, store it in a variable this way:

    SET ORIGINAL=%CD%
    

    and use %ORIGINAL% later, for example:

    dir /b *.tex > %original%\%2.txt