I've just been playing with dirs, pushd and popd. Adding/navigating directory with pushd , using dirs -v to show a vertical list of the directory 'stack', and popd to remove an entry from the list. When I open a new terminal and list the directories with dir or dir -v , the new terminal only shows the current directory. Is there any way to transfer the list when opening a new terminal? I'm on Debian Stretch with xfce4-terminal.
1 Answer
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 "${v[i]}" >/dev/null
done
It would make sense to save this code in a bash function and call it from your ~/.bashrc
.
-
I ran the command dirs -p >~/.mydirs ... then put those five lines into a bash script and made it executable (I changed mydirs to .mydirs). I opened a new terminal and ran the script and it didn't work. Am I doing something wrong?– oksageCommented Dec 23, 2018 at 16:52
-
Remember that running a script causes bash to fork a copy of itself to execute the commands in it. To make bash execute commands from a file
abc
in the current directory use the bash commandsource ./abc
instead of./abc
. Or you can put the five lines into a shell function in your~/.bashrc
and then, in any new bash shell, just type the name of the function.– meuhCommented Dec 23, 2018 at 17:23