Bash Tips and Tricks #1

Below are a few aliases that I use almost everyday at work:

  • Navigating directories
    alias ..='cd ..'
    alias ...='cd ../..'
    alias ....='cd ../../../..'
    alias .....='cd ../../../../..'
    

    With these aliases in place, use “..” to navigate one-level up, “…” to navigate two-levels up, etc.

  • Navigating to project related directories
    alias cdtomcat='cd "/cygdrive/c/appservers/tomcat"'
    alias cdlogs='cd "/cygdrive/c/appservers/tomcat/logs"'
    alias cdws='cd "/cygdrive/c/satish/eclipse/workspace"'
    

    To navigate to Tomcat logs directory, type “cdlogs” at the command prompt; To navigate to project workspace, type “cdws”. You get the idea, right?

  • Converting cygwin directory in to windows format
    alias cpwd='echo $PWD | sed -e "s/\/cygdrive\/c/c:/g" | sed -e "s/\//\\\/g"'
    

    Look at the screenshot below to get an idea

  • Open windows explorer
    alias winexp='explorer.exe `cpwd`'
    

    typing “winexp” at the command prompt will open windows explorer in the current working directory — this alias uses cpwd alias set up above

  • The cd command in cygwin takes directory that is in cygwin path format. For example, to navigate to C:\Satish\Software, the command is “cd /cygdrive/c/Satish/Software”. Below is a tiny function that changes to a directory given path in windows format (e.g. c:\Satish\Software)
    function wincd(){
    	dir=`echo "$1" | sed -e 's/\\\\/\\//g'`
    	cd $dir
    }
    

    Command wincd “C:\Satish\Software” changes the working directory to /cygdrive/c/Satish/Software — note that double quotes around the path are required. See picture below:

Find Jars

Below is a tiny bash function to find jar file(s) containing a particular class:

function findjars(){
	for i in `find . -type f -iname "*.jar"`; do
		count=`jar tvf $i | grep -i $1 | wc -l`;
		if [ $count -ge 1 ]; then
			echo $i;
		fi;
	done;
}

I have added this function in .bashrc file in home directory and whenever I need to fnd a jar containing a particular class, I just type findjars classname (e.g. findjars BasicDataSource)