Thursday, June 26, 2008

Super Bash Tricks

I'll start off this blog with some good bash shell tricks. You'll be the envy of your friends with these up your sleeve.

For the uninitiated, bash is the default shell in many Linux distros, including Fedora, Ubuntu, Redhat etc. If you use a Linux based OS, then chances are that you are using bash. For this reason, I outline below a few common annoyances, and the simple ways to overcome them.

1. Lost bash history

If you have a terminal open and are typing commands, then open another one and use that for a while, the new terminal won’t remember any of the commands typed in the first one. In addition, closing the first terminal, and then the second will overwrite any of the commands typed in the first terminal. Doubly annoying! This happens because the bash history is only saved when you close the terminal, not after each command. To fix it:


Edit your .bashrc (for beginners, any file starting with a . is hidden - they contain user preferences.)

nano ~/.bashrc

No need for a sudo here Ubuntuers, this is your own file, not a system setting. I like nano, but it’s up to you, choose gedit, kate, mousepad, vi or emacs as you wish.add the lines

shopt -s histappend

PROMPT_COMMAND=history -a;

And save. (control - O to write out. ^ means control in nano and other software, so the bottom of the editor does actually make sense to beginners! ^X to exit.) This makes bash append history instead of overwriting it, and makes it so that each time the prompt is shown it writes out all the history.

2. Stupid spelling mistakes

Add


shopt -s cdspell


to your .bashrc again. This will make sure that spelling mistakes such as ect instead of etc are ignored.

3. Duplicate entries in bash history


I often type cd .. multiple times in a row, when I then press UP to go back to earlier commands I don’t want to be reminded of my earlier inelegant excursions around the file system.
Add


export HISTCONTROL="ignoredups"


to .bashrc again.
Even better, add


export HISTIGNORE="&:ls:[bf]g:exit”


This will ignore duplicates, as well as ls, bg, fg and exit as well, making for a cleaner bash history.

4. Multiple line commands split up in history


Add


shopt -s cmdhist


to .bashrc, this will change multiple line commands into single lines for easy editing.


5. A couple of neat extras suggested by commenters


Press control + R in bash, then start typing and you can search through your past commands much easier than just pressing UP 300 times…
Alternatively, use


history grep "foo"


to search through your history - “foo” is the thing you are searching for. (Thanks to Ally)


cd -


goes to the last directory you were in - useful if you want to go somewhere to change something, then need to quickly flip back again.

Conclusion So, there are a few tips to get your bash history more manageable - if you have any extra tips, add them to the comments and I’ll add them to the main article!

No comments: