Archive

Archive for January, 2012

Bash alias and functions

January 13, 2012 Leave a comment

I made a quick reference to alias in my previous post and thought I’d expand on that a little more and introduce bash functions as well. alias and function are two ways to automate simple commands and reduce the amount of typing you do each and every day. Some of these commands I used to type out 20x a day and got annoyed at having to type so much. All of the alias and function definitions are in my .bash_profile script so they get loaded every time I login (.bashrc should also work).

The big takeway here is how alias differs from function.

  • An alias is processed at the time of its definition and therefore cannot take arguments.
  • A function is processed at runtime and can process arguments.

rgrep is real command (grep -r) but I wanted to add a few other default parameters. To speed up searches I like to exclude .svn and vendor (gem bundler) folders. All I want to type is what I’m searching for and the files/folders I want to search.

function rgrep() {
   rgrep -n --exclude-dir=.svn --exclude-dir=vendor $1 $2
}
# Search all = *
function agrep {
   grep -nr --exclude-dir=.svn --exclude-dir=vendor $1 *
}
# Search case-insensitive (-i), all (*)
function aigrep {
   grep -nri --exclude-dir=.svn --exclude-dir=vendor $1 *
}

jheth@dev:~$ rgrep substr ~/project/
jheth@dev:~$ agrep substr
jheth@dev:~$ aigrep ClassName

As mentioned in my previous post, I used alias to cd into the proper directory and run the watchr process. I also made one to edit the watchr configuration file.

alias watchem='cd ~/project/ && ./test/bin/watchr ./test/tests.watchr.rb'
alias editwatch='vim ~/project/test/tests.watchr.rb'

jheth@dev:~$ watchem

Every once in a while GLaDOS (jabber bot) misbehaves and I need to kill the process. At first I was running 2 commands to do this, grep + kill. I then created this one liner but I never want to type this out manually.

function killbot() {
   kill `ps -ef | grep glados.rb | grep -v grep | awk '{print $2}'`
}

jheth@dev:~$ killbot

I manage all of our remote deployments, svn merges, and various remote tasks through Capistrano now. I got tired of changing directories just to run the command so I turned it into a function.

function capy {
   pushd `pwd`
   cd ~/github/release-scripts && ./bin/cap $1
   popd
}

jheth@dev:~$ capy update:web:staging

I hope this sparks some ideas for the repitive commands you run each day. Feel free to post comments as suggested aliases or functions.

Categories: Uncategorized Tags: