Thursday, September 20, 2012

A simple Bookmark Script for Bash

Ever since I started using bash, I have felt the need for a bookmark system. One day, I went to omniscient Google and prayed for help. Sadly, I wasn't really happy with the results*. Finally, I wrote a script** and here it is:


fileName="${HOME}/.markedLocations.txt"
flag=0
if [ "${1}" = "." ]; then
   pwd >>${fileName}
   flag=1
fi
if [ "${1}" = "s" ]
then
   touch ${fileName}
   line_no=1
   color1='\e[1;35m'
   color2='\e[1;32m'
   while read line
   do
      color=$color2
      if [[ $(($line_no%2)) -eq 1 ]]; then
         color=$color1
      fi
      echo -e $color"${line_no}\t"$line;
      line_no=$(($line_no+1))
   done < ${fileName}
   echo -en '\e[0m';
   flag=1
fi
if [[ "${1}" =~ ^[0-9]+$ ]]; then
   pathCmd="awk "FNR==${1}" ${fileName}"
   path=`${pathCmd}`
   if [[ "${path}" = "" ]]; then
      echo "NO MARK"
   else
      cd ${path}
   fi
   flag=1
fi
if [ "${flag}" = "0" ]
then
   cat -n ${fileName} 2>/dev/null|grep -i $1
fi

Save this in a file named something.sh(or whatever you like)
Add the following in your ~/.bashrc :


alias mark="source /path-where-you-saved/something.sh"

Open a new bash and try the follwoing:
mark .  (it will add the current directory to bookmark file)
mark s  (it should show the numbered list of bookmarks)
Now cd to some other directory and try:
mark 1 (it should take you to the directory where you gave mark .)
mark pattern (will show you marks matching "pattern" )

The following screenshot will give you a better idea of how it works.

Enjoy !

*  Out of all the results, I found this one  to be simple enough to give a try.
** Thanks to Pravin for all the help related to bash scripting.

2 comments: