May 16, 2012

push & pop - cd made bit easier

During my initial days as developer, I found myself doing cd to folders which were deep in the directory structures often having long names. Long names were not a big problem due to auto completion but remembering different directory names were a problem. The idea of having aliases for cd for different directories was dropped even before writing a single alias as I didn't want to remember the aliases for different directories. So I wrote two scripts named push.sh and pop.sh. The working is pretty simple, you go to a directory which need to be remembered, execute push. The pop script will give a list of remembered directories and based on the choice will take you to the selected directory. I hope you may find this useful. Here are the scripts:

[prime@ford bin]$ cat push.sh 
#! /bin/bash
lines_to_keep=9
data_file=~/.dir.dat
tmp_file=~/.dir.dat.$$ 
tail -"$lines_to_keep" $data_file > $tmp_file
mv $tmp_file $data_file
cur_dir=`pwd`
echo $cur_dir >> $data_file

[prime@ford bin]$ cat pop.sh 
#! /bin/bash
lines_to_keep=9
data_file=~/.dir.dat
tail -"$lines_to_keep" $data_file |nl
echo -e "Choice please : " \\c
read choice
case "$choice" in
[0-9]*)
        ;;
*)
        echo "Invalid choice"
        return 0
        ;;
esac
dest_dir=`tail -"$lines_to_keep" $data_file | head -$choice |tail -1`
cd $dest_dir

Save scripts in a convenient location say ~/bin. The pop.sh script need to run in the current shell the cd to work correctly. This can be either be done by preceding the pop.sh with a dot (not very convenient) or creating an alias which will run the script in the current shell as follows

alias pop='. ~/bin/pop.sh'
alias push='~/bin/push.sh' # Put these aliases in the .bashrc or .profile

Hope you may find it useful. Share and enjoy!*

* "Share and Enjoy" is the slogan of the Sirius Cybernetics Corporation ;)

No comments:

Post a Comment