You could save the list of directories in a file, one per line, and restore them in the new shell by repeatedly doing pushd
on each line. This assumes you do not have directories with newlines in the name.
bash does have a builtin variable DIRSTACK
that holds the list of directories, but sadly it is not of much use as you cannot add new elements to this array (though you can change existing entries).
So to save the list simply do
dirs -p >~/mydirs
Restoring them is a bit more complex. First we read the file into an array v
, then traverse it in reverse order until entry index 1. I've stopped at index 1 rather than 0 as the 0th entry will just be the current directory at the time you did dirs -p
. You can choose if you want this or not.
dirs -c # clear IFS=$'\n' read -r -d '' -a v <~/mydirs for ((i=${#v[*]}-1; i>=1; i--)) do pushd -n "$" >/dev/null done
It would make sense to save this code in a bash function and call it from your ~/.bashrc
.