Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pushd popd global directory stack?

Tags:

shell

I do not know if there is a valid way to do this. But, have always wanted to see if its possible.

I know that pushd, popd and dirs are useful for a number of things like copying between directories you have recently visited.

But, is there a way in which you can keep a global stack? So that if I push something (using pushd) in one terminal it gets reflected in another (maybe only the terminals in that login session).

like image 717
Raghuram Onti Srinivasan Avatar asked Mar 28 '12 22:03

Raghuram Onti Srinivasan


2 Answers

You should be able to do this with a pair of shell functions and a temporary file.

Your temporary file would be named something like '/home/me/.directory_stack' and would simply contain a list of directories:

/home/me
/etc
/var/log

Your 'push_directory' function would simply add the current directory to the list. The 'pop_directory' function would pull the most recent off of the list and switch to that directory. Storing the stack in a file like this ensures that the information exists across all open terminals (and even across reboots).

Here are some example functions (warning: only lightly tested)

directory_stack=/home/me/.directory_stack
function push_dir() {
    echo $(pwd) >> $directory_stack
    cd $1
}
function pop_dir() {
    [ ! -s $directory_stack ] && return
    newdir=$(sed -n '$p' $directory_stack)
    sed -i -e '$d' $directory_stack
    cd $newdir
}

Add that to your .bashrc and they'll automatically be defined every time you log into the shell.

like image 55
bta Avatar answered Oct 29 '22 01:10

bta


You'll probably want to write a few shell functions and use them in place of pushd and popd. Something like the following (untested) functions might do the job:

mypushd() { echo "$1" >> ~/.dir_stack ; cd "$1" }
mypopd() { dir=`tail -1 ~/.dir_stack` ; cd "$dir" ;
           foo=`wc -l ~/.dir_stack | egrep -o '[0-9]+'` ;
           ((foo=$foo-1)) ;
           mv ~/.dir_stack ~/.dir_stack_old ;
           head -n $foo ~/.dir_stack_old > ~/.dir_stack }

You could get rid of some of the uglier bits if you write a small program that returns and removes the last line of the file.

like image 27
sarnold Avatar answered Oct 29 '22 02:10

sarnold