Archive for May, 2009

A few handy things to know about bash

Friday, May 15th, 2009 By: Daniel

Pipes and Redirection

These are standard shell tools, but sometimes I get confused about which one I need. So my way of thinking about it is that pipes are a connection between programs while redirection always goes to (or from) a file.

So, for example, in order to find all my session routes I would connect the rake and grep commands via a pipe:

  rake routes | grep session

On the other hand, I would use redirection to save the output of a git diff to a file so as to be able to feed it in to the patch program (which expects its input on standard in).

  git diff > patchfile
  patch < patchfile

Braces

I just learned about these recently and they make renaming things so much easier!

  mv file.old file.new # old way
  mv file.{old,new} # does the same thing!

So creating your database.yml file from the example one is as easy as:

  mv config/database.yml{.example,}

Changing Directories

I assume everyone already knows that cd with arguments goes to your home directory (the contents of the $HOME environment variable), but did you know you can do 'cd -' to go to the previous directory you were in ($OLDPWD)?

  :/var/www$ cd /etc/apache2/sites-enabled/
  :/etc/apache2/sites-enabled$ cd -
  /var/www
  :/var/www$

History

!! # execute the previous command (great for when you forget to sudo something)
!$ # The last argument of the previous command
!^ # The first argument
!* # All the previous arguments
^old^new^ # Repeat the previous command replacing old for new

And lots, lots more! See 'man history' for details.

Keyboard shortcuts

Here are a few of the keyboard shortcuts that I use regularly (copied from the wikipedia article http://en.wikipedia.org/wiki/Bash):

CTRL + l : clears the screen content (equivalent to the command : clear).
CTRL + u : clears the line content before the cursor and copy it in the clipboard.
CTRL + k : clears thctrl alt copy pastee line content after the cursor and copy it in the clipboard.
CTRL + w : clears the word before the cursor and copy it in the clipboard.
CTRL + y : (yank) adds the clipboard content from the cursor position.