28

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?

Brian
  • 14,610
  • 7
  • 35
  • 43
One Two Three
  • 22,327
  • 24
  • 73
  • 114

4 Answers4

70

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.

Community
  • 1
  • 1
Levon
  • 138,105
  • 33
  • 200
  • 191
  • Thanks. The `pushd` and `popd` would work! :) But is there a way to turn off the echo? (ie., let those commands execute 'quiety'?) – One Two Three May 18 '12 at 16:01
  • 2
    @OneTwoThree I don't know as I usually use `cd -`. However, you could alwayd do something like `pushd > /dev/null` as a work around. If you are putting this into a script, there may be an option to silence your shell. – Levon May 18 '12 at 16:09
  • 1
    this site http://www.linuxmisc.com/12-unix-shell/7d94a90c6614ef93.htm suggests putting `pushd_silent=true` into `$HOME/.bashrc`, not sure if that will work though. – Levon May 18 '12 at 16:12
4

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.

Barton Chittenden
  • 4,238
  • 2
  • 27
  • 46
  • +1 in principle, but have you _measured_ a performance hit? Since every command that isn't a shell built-in will do a fork, I doubt that the fork for a subshell is likely to incur any significant performance penalty. – Norman Gray May 19 '12 at 19:55
1

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

kalikid021
  • 210
  • 1
  • 6
0

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.