Created: Sun Mar 24 18:10:14 CET 2019
Last modiﬁed: Sun Mar 24 19:34:41 CET 2019
While automating some tedious task, you might have written scripts that would often begin like this:
and that would often end like this:
cd $OLDPWD # or even ~ or $HOME
I made such scripts to automatically upload my posts to Neocities
without always changing directory manually. (The scripts that manage my
blog are in the same directory as my posts; not in
The issue is that
$OLDPWD is not available everywhere. For example, it
does exist in Bash but is reference as
$owd in the C Shell (tcsh
Also, if your script calls
cd several times or run other scripts
which can fail before changing to the old directory, you can get
Here is where
popd come in. They are almost always shell
builtins, just like cd(1).
pushd will push the current directory on the “directory stack” and
will run cd(1) on its argument.
popd will run cd(1) on the last directory that have been pushed and
remove it from the stack.
Here is an example case from my own workﬂow:
pushd $PATH_TO_MY_BLOG ./custom_scripts/build_last popd
build_last script requires the current directory to be
$PATH_TO_MY_BLOG. Since I usually edit posts from
custom_scripts/edit_post, I don’t really need that one.
Except I do.
Since I’ve learned about
popd I started rewriting all of
Basically, this couple of builtins allows you to always return to the
directory you called the alias from. Now I can
editlast from any place.
But what if your script calls another?
Since directory are pushed onto a stack, in a FILO (First In Last
Out) fashion, it means that
popd will undo the most recent
It means that if a script
A that uses this trick calls a script
that also uses the same trick, it will work.
It all works well provided your script doesn’t terminate before
has been called.
I recommend setting up a
(Bash feature) to transparently run
popd in case of failure or just to
leave it as it is and debug your script from the directory it failed in.
For further reference, I copy-pasted the relevant parts of csh(1) in a text ﬁle.
Don’t hesitate to share advices or similar tricks in the comment section right below.