Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

batch-file

dos

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

  • %1 represents a path relative to the current directory.
  • %2 represents a filaname.

Assume the current directory is father\me\.

User can use this batch as follows:

  • batch child/grandchild log
  • batch ../brother log

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 2 arguments. cd %1 dir /b *.tex > <original directory>\%2.txt 

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

like image 611
xport Avatar asked Aug 09 '11 00:08

xport


People also ask

How do I return to the original directory?

cd - returns to the previous directory. If you want to go to home dir specifically, use cd , cd $HOME , or cd ~ .

How do I change the working directory in a batch file?

Under Windows-10, go to All Apps, Windows System and the open the Command Prompt window. From the command prompt change directory to the batch file directory: cd \Tutorial\batch. Then type the name of the batch file test_conc followed by Enter.

How do I change directories in command prompt?

Just use cd /d %root% to switch driver letters and change directories. Alternatively, use pushd %root% to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd to switch back.


1 Answers

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 
like image 199
Aacini Avatar answered Sep 22 '22 00:09

Aacini