Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

unix

cd

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?

like image 477
One Two Three Avatar asked May 18 '12 15:05

One Two Three


2 Answers

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.

like image 93
Levon Avatar answered Oct 21 '22 15:10

Levon


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.

like image 26
Barton Chittenden Avatar answered Oct 21 '22 15:10

Barton Chittenden