One Two Three
One Two Three

Reputation: 23497

get back to the previous location after 'cd' command?

I'm writing a shell script that needs to cd to some location. Is there any way to get back to the previous location, that is, the location before cd was executed?

Upvotes: 28

Views: 21418

Answers (4)

Robert Krten
Robert Krten

Reputation: 3

Another alternative is a small set of functions that you can add to your .bashrc that allow you to go to named directories:

# cd /some/horribly/long/path
# save spud
# cd /some/other/horrible/path
# save green
...
# go spud
/some/horribly/long/path

This is documented at A directory navigation productivity tool, but basically involves saving the output of "pwd" into the named mnemonics ("spud" and "green") in the above case, and then cd'ing to the contents of the files.

Upvotes: 0

Barton Chittenden
Barton Chittenden

Reputation: 4416

If you're running inside a script, you can also run part of the script inside a sub-process, which will have a private value of $PWD.

# do some work in the base directory, eg. echoing $PWD
echo $PWD

# Run some other command inside subshell
( cd ./new_directory; echo $PWD )

# You are back in the original directory here:
echo $PWD

This has its advantages and disadvantages... it does isolate the directory nicely, but spawning sub-processes may be expensive if you're doing it a lot. ( EDIT: as @Norman Gray points out below, the performance penalty of spawning the sub-process probably isn't very expensive relative to whatever else is happening in the rest of the script )

For the sake of maintainability, I typically use this approach unless I can prove that the script is running slowly because of it.

Upvotes: 4

kalikid021
kalikid021

Reputation: 210

You could echo PWD into a variable and the cd back to that variable. It may be quieter.

Upvotes: 1

Levon
Levon

Reputation: 143037

You can simply do

cd -

that will take you back to your previous location.

Some shells let you use pushdir/popdir commands, check out this site. You may also find this SO question useful.

Upvotes: 73

Related Questions