4

Ok this is a short question. I just happened to know that with pushd command, we can add more working directories into our list, which is handy. But is there a way to make this list permanent, so it can survive reboots or logoffs?

  • 2
    Well you can write a little script to be ran at log in to accomplish that. – M. Becerra May 16 '17 at 10:52
4

You may pre-populate the directory stack in your ~/.bashrc file if you wish:

for dir in "$HOME/dir" /usr/src /usr/local/lib; do
    pushd -n "$dir" >/dev/null
end

or, if you want to put the directories in an array and use them from there instead:

dirstack=( "$HOME/dir"
           /usr/src
           /usr/local/lib )

for dir in "${dirstack[@]}"; do
    pushd -n "$dir" >/dev/null
end

unset dirstack

With -n, pushd won't actually change the working directory, but instead just add the given directory to the stack.

If you wish, you can store the value of the ${DIRSTACK[@]} (upper-case variable name here), which is the current directory stack, into a file from ~/.bash_logout, and then read that file in ~/.bashrc rather than using a predefined array.

In ~/.bash_logout:

printf '%s\n' "${DIRSTACK[@]}" >"$HOME/.dirstack"

In ~/.bashrc:

while read dir; do
    pushd -n "$dir" >/dev/null
done <"$HOME/.dirstack"

I don't know how well this would work in a situation where you use multiple terminals. The .dirstack file would be overwritten every time a terminal exited, if it ran a bash as a login shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.