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?
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 $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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With