Linux Tips 1: Useful .bashrc commands for managing command history and saving key strokes

I thought I would share some of my Linux, specifically Ubuntu Linux, configuration settings that help me in my everyday productivity. I am not sure how many tips there are but I plan to keep writing until I have covered just about everything I know.

The first tip I have is about ~/.bashrc, which a file in your home directory that is loaded up as soon as you login, making it useful for setting custom settings such as aliases and environment variables. If you use Bash as your shell this will be useful to you; even if you don't some commands may have equivalents. I also use these commands in .bash_profile on my OS X machine.

To start, I will introduce the bash commands are used in this tip, they are:

alias hs="history | grep "
PS1="[\! \u:\w] "

The first two lines of the command help you set your command line history file size and the number of commands the history file will store; you can find this file in ~/.bash_history.

If you look in .bash_history you will find many commands you previously typed. Alternatively type history in the command line to have it printed out automatically.

The third line makes use of the history command by piping it to grep and then saving that as an alias called hs. With just the first three lines you can quickly find the text that previously typed. For example when I type hs doc on my computer I get the following output:

[536 paul:~] hs Doc
503 cd Documents/
536 hs Doc

This output shows that in my command history record number 503, I typed cd Documents/ to access the documents folder. Now if I did not want to type all that again all I need to do is type !503 and the same command will be executed from where I currently am. I have used a very simple example, but the longer your command the more time this saves you.

The most regular use I have for this is when editing multiple files in Cake PHP, so I would tell ViM to edit a controller, view, and relevant Javascript file all in one command, then if I need to edit that page again I can just search for the controller name in my history and I can immediately access all relevant files.

Back to the original .bashrc file, the final fourth line allows my prompt to look like [536 paul:~], which contains both the command history number, my currently logged in account, and the file system path I am currently in. So if I wanted to repeat what I typed just then I can type !536 and be done with it.

That concludes my tip for today. Hopefully you find it useful. By the way, you can also retype a series of commands if your initial command is linked with &&. For example I often do bzr merge ../dev && bzr ci -m "Merged from development branch" to quickly bring a live version of the code I am working on up to date using Bazaar Version Control.


Post a Comment