Dan Mehra
Dan Mehra

Reputation: 225

going back to directory

My current directory is

C:/users/admin/temp

Next, I navigate to

C:/users/admin/temp/1/2

How do I get back to temp without using pushd command at temp and just go to temp with one command without going home or doing cd ~?

Upvotes: 22

Views: 86672

Answers (5)

js2010
js2010

Reputation: 27443

I like how zsh does it. You can do cd -2 to go to the second entry in the directory stack. http://zsh.sourceforge.net/Intro/intro_6.html

This is as close as I can get in pwsh, after using pushd a few times:

$a = pwd -stack
cd $a.toarray()[1]

I like to alias cd to pushd in $profile. Then I type popd when I want to go back.

set-alias cd pushd -option allscope

I'm liking this method lately, "cd-" without a space in between:

set-alias cd pushd -option allscope
set-alias cd- popd -option allscope

Upvotes: 1

Bacon Bits
Bacon Bits

Reputation: 32170

Use Push-Location and Pop-Location instead of cd (aka, Set-Location).

Or, if you just want to traverse up the directory heirarchy two levels, you can use cd ..\...

Upvotes: 21

MarredCheese
MarredCheese

Reputation: 20811

The built-in commands cd +/cd - are great but kind of a pain to use repeatedly. Here are some wrappers to make them easier/faster to use:

Function b([int]$n = 1) {
    foreach ($i in 1..$n) { cd - }
}

Function f([int]$n = 1) {
    foreach ($i in 1..$n) { cd + }
}

# runs "cd -"
b

# runs "cd +; cd +; cd +"
f 3

And here is a function for going up one or multiple levels (in one step):

Function u([int]$n = 1) {
    cd (@('..') * $n -join '/')
}

# runs "cd .."
u

# runs "cd ../../.."
u 3

And the pushd/popd aliases are too long for my taste:

Set-Alias pu Push-Location
Set-Alias po Pop-Location

Upvotes: 3

David Hatch
David Hatch

Reputation: 3116

With Powershell Core 6.2.2 or later you can do cd - to navigate to your previous directory.

cd is the alias for Set-Location. Adding paramerter + or - goes forward or backward through your location history.

Powershell Docs - Set-Location

Upvotes: 8

dan-gph
dan-gph

Reputation: 16909

A useful tool is z. You could type z temp, and z would take you back to the temp folder. It uses some guesswork to work out where it thinks you want to go to, using an algorithm based on frequency and recency, but it almost always guesses correctly.

Upvotes: 4

Related Questions