It would be good to have a log of the last N directories visited in variables like cd1, cd2, cd3, ... cd9.<p>These could be interpolated into commands:<p><pre><code> $ cd somewhere # found via CDPATH
/path/to/somewhere
$ cp $cd1/file.txt . # copy file from where we were just before the cd, to here
</code></pre>
cd1 would be always the most recent, cd2 second most recent.<p>Here it is up to cd4:<p><pre><code> if [ -z "$c1" ] ; then
c4=
c3=
c2=
fi
cdlog_chdir()
{
local cur=$PWD
if command cd "$@" ; then
c4=$c3
c3=$c2
c2=$c1
c1=$cur
fi
}
cdlog_chdir()
{
local cur=$PWD
if command cd "$@" && [ "$PWD" != "$cur" ]; then
# only if we successfully change to a different
# directory do the following
if [ "$cur" == "$c2" ] && [ "$PWD" == "$c1" ] ; then
# Special case: if we changed to the directory that is second
# in the cdlog, then just swap between those two.
c2=$PWD
c1=$cur
else
# Otherwise rotate through all four.
c4=$c3
c3=$c2
c2=$c1
c1=$cur
fi
fi
}
</code></pre>
Tip: in bash use ESC Ctrl-E to expand variables in the command line before running it. Then the command is recorded with concrete paths, rather than variables that are changing. You can recall the command from history to repeat it.<p>Handy aliases:<p><pre><code> alias cd='cdlog_chdir -P'
alias cs='cdlog_chdir "$c1"'
</code></pre>
"cs" goes back to the previous; if that is repeated, it triggers the swapping behavior in cdlog_chdir, hence the "cs" name.