lakecityransom
lakecityransom

Reputation: 85

How to do pushd and popd in a directory

The following batch file works with an incoming argument to get the first path.

Code:

echo A. we started at = %cd%
set current=%cd%
pushd ..
echo #1 pushed to = %cd%
set parent=%cd%
pushd ..
echo #2 pushed to = %cd%
set grandparent=%cd%
echo .
if %argC% NEQ 10 (
  echo the if statement starts at = %cd%
    pushd ..
    echo if statement: #3 pushed to = %cd%
    popd ..
    echo if statement: #4 popped to = %cd%
    popd ..
    echo if statement: #5 popped to = %cd%
)
echo .
echo B. after the if statement we start back at: %cd%
popd ..
echo #6 popped to = %cd%
popd ..
echo #7 popped to = %cd%

Result:

A. we started at = C:\test\test-layer-2\files
#1 pushed to = C:\test\test-layer-2
#2 pushed to = C:\test
.
the if statement starts at = C:\test
if statement: #3 pushed to = C:\test
if statement: #4 popped to = C:\test
if statement: #5 popped to = C:\test
.
B. after the if statement we start back at: C:\test\test-layer-2
#6 popped to = C:\test\test-layer-2\files
#7 popped to = C:\test\test-layer-2\files
Press any key to continue . . .

Question: Why does the if statement not reflect %cd% correctly? *Removing #1 or #2 affects the path outputted in #3, #4, #5. *Changing pathing with #3, #4, #5 only properly outputs the result on line B.

Upvotes: 0

Views: 3689

Answers (2)

Honguito98
Honguito98

Reputation: 694

You need use SetLocal EnableDelayedExpansionat top of your batch file. Remember that any change with variables into a code block e.g. an ifsentence, for,etc.

Then you need use ! characters instead %:

...
echo if statement: #5 popped to = !cd!
...

Upvotes: 0

Stephan
Stephan

Reputation: 56180

When you use a variable inside a block (between (and ), you need to enable delayed expansion:

setlocal enabledelayedexpansion
set var=hello
if "a"=="a" (
  set var=world
  echo %var% !var!
)

same with your %cd%

Upvotes: 3

Related Questions