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

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


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.


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 $PWDecho $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.


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