Bash tips and tricks
25 11 2007For 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.
Pressing Esc . brings up the last object you referred to. For instance, if you had just typed cat /etc/apt/sources.list , then typing rm then pressing esc . would auto complete to rm /etc/apt/sources.list . Best way is to try it I reckon! (Thanks to Andrew.)
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!

Thanks for the tips. Though I use the terminal only once in a while, I (and many others with me I guess) prefer not to use it…. at least 90% percent of the persons that use computers panic if there is no mouse…….command line? what’s that?
But thanks anyway!
Cheers,
Maarten
Excellent info, the way history was handled was pretty annoying but I hadn’t got around to looking whether it could be changed in any way, you just saved me a job and for that I thank you :]
[...] Basic bash setup tips Filed under: Linux, OSX — 0ddn1x @ 2007-11-25 23:39:10 +0000 http://richbradshaw.wordpress.com/2007/11/25/bash-tips-and-tricks/ [...]
I have been using linux now for about three years. This is a great set of tips!!
The best set of bash tips:
* emerge zsh
* apt-get zsh
* yum zsh
…
Zsh does all this and more, like floating point math, for ((i=0; i<aval; i++) loops, “prog | read aval” (and aval is useable in rest of script), etc.
You rock man, thanks for the hot tips. U saved lot of time for us. Thanks
Eliena Andrews
[...] simmosays wrote an interesting post today onHere’s a quick excerpt [...]
[...] read more | digg story [...]
Same here … saved a job… was wanting to get to history overwriting for some time now. Thanks.
Good bash tips. I’ve also got some miscellaneous bash tips at my site:
http://marc-abramowitz.com/archives/category/computers/software/unix/bash/
Try this:
$ history | grep "foo"Where “foo” is what you want to find in your recent history. Useful if it was a complicated command.
Marten:
Mice are for window management (focus-follows-mouse ftw!) and photo-editing only. Anything else, the terminal can do much faster. I’d feel right at home with no mouse as long as I had a nice bash shell (Windows’ big suckage point for me is its shitty shell).
The history cleaner-uppers look pretty useful. Thanks!
Metagg is tracking this post
Find out what Social News Sites are discussing this post over at metagg.com
[...] 2.Cool bash tricks and tips : actually i want to write how to coloring bash in linux ,but it’s an old tricks so this one is not just ordinary bash tricks(i hope ;D) http://richbradshaw.wordpress.com/2007/11/25/bash-tips-and-tricks/ [...]
I use Ctrl+R alot for a bash history search. Open a terminal, press Ctrl+R, start typing a recent command and it will find it for you
Helpful tips. I love to customise the shell on my home system as much as I want, and while that is done both out of convenience and taste, it runs the risk of ruining my habits when I have to sit behind other shells or shells on other systems where my customisations are either not available.
[...] Richard posted some nice tips about bash history.. [...]
Here are my commented bash settings:
http://www.pixelbeat.org/settings/.bashrc
http://www.pixelbeat.org/settings/.inputrc
Just to pin point, bash is not the default shell on Ubuntu since 6.10
I don’t have any tips for you but I do have a question. How does one go about getting un-hitched from the MS wagon without trashing all your computer stuff? I mean you practically MUST have a computer to pay bills and shop and things…Is there a good way to flip it?
Here’s a frame of reference for the question: I was thinking about this yesterday: the last Microsoft operating system I really liked was MS DOS 6.x–any suggestions?
If you want to just copy paste here is the code compiled for this purpose.
# Bash tips and tricks for History related preferences
# see http://richbradshaw.wordpress.com/2007/11/25/bash-tips-and-tricks/
# == 1 Lost bash history ==
# the bash history is only saved when you close the terminal, not after each command. fix it..
shopt -s histappend
PROMPT_COMMAND=’history -a’
# == 2. Stupid spelling mistakes ==
# This will make sure that spelling mistakes such as ect instead of etc are ignored.
shopt -s cdspell
# == 3. Duplicate entries in bash history ==
# This will ignore duplicates, as well as ls, bg, fg and exit as well, making for a cleaner bash history.
export HISTIGNORE=”&:ls:[bf]g:exit”
# == 4 Multiple line commands split up in history ==
# this will change multiple line commands into single lines for easy editing.
shopt -s cmdhist
Esc .! Typing this into the bash shell brings up the last “word” from the previous command. Often that’s the file or object you are dealing with. Note you can also use Esc and “_” but typing “_” requires a shift - “.” doesn’t. So then you can do stuff like:
$ ls file
$ more file
$ rm file
The object here is “file”. So you probably typed “ls file” or did filename completion. Then you say to youself “Hmmm what’s in file?” and type more. Just type Esc . and file will be filled in for you. Of course, file can be some real long path too. After looking at the contents of file you decide to get rid of it so you type rm then Esc . again recalling file.
thanks for the tips.
Alternatively to the ctrl+R, a simple way to recall a command you’ve done earlier is :
!xxx
where “xxx” are the first few letters of the command.
Thanks for the tips. Never use before.
Cool tips mate, I think I’ll try some. Check out my blog at http://www.extrapreneur.wordpress.com
[...] Basic bash setup tips Filed under: Linux, OSX — 0ddn1x @ 2007-11-26 15:49:53 +0000 http://richbradshaw.wordpress.com/2007/11/25/bash-tips-and-tricks/ [...]
[...] Оригинал: bash tips and tricks [...]
[...] history preferences See this blogpost for tips on modifying BASH command line history [...]
Ctrl+R is part of series of shortcuts that come from emacs, so just learn emacs and you learn to better manipulate the bash shell. Like Ctrl+w, Ctrl+d, Alt+d, Ctrl+y, Ctrl+a, Alt+a, Ctrl+e, Alt+e, etc. etc….hell it evens supports undo try Ctrl+_
Or if your more a vi person just do set -o vi and follow the same principle.
Another nice tip: ^foo^bar to substitute foo by bar in the previous command
I entered these commands and later when I started terminal which was after I rebooted the system I got the following error.
bash: -a’: command not found
rungss@rungss-ubuntu:~$ gedit ~/.bashrc &
this I suppose was because of the line
PROMPT_COMMAND=’history -a’
any idea why this is happening??
For getting the last object referred to, another way to do (that’s slightly quicker/easier to type than ESC + .) is:
Alt + . (I find it a lot easier to hit alt + . as to get escape requires moving hands quite a bit from the home row)
By far the coolest bash trick, (that I only learnt about last year) is repeating multiple parts of the commant with curly brackets {}. Ie, if you are in home and need to quickly make a backup copy of /etc/apache2/httpd.conf (to pick a file at random), instead of typing
cp /etc/apache2/httpd.conf /etc/apache2/httpd.conf.bakyou can type
cp /etc/apache2/httpd.conf{,.bak}I use that trick a *lot*.
@rungss: make sure you use a normal ' not a ‘ - I’ve changed the text above to make it work properly now.
[...] Bash tips and tricks « Richard’s linux, web design and e-learning collection wonderful stuff people - bash is not scary, its a doorway to power and control. (tags: bash blog command commandline commands history howto job sysadmin unix linux shell tips) [...]
I like beans
[...] Bash tips and tricks « Richard’s linux, web design and e-learning collection (tags: ubuntu shell commands bash linux tips unix howto sysadmin productivity documentation my_settings dev_environment) [...]
Great tips, mate!
when trying to track down a file(s) that are hogging up disk space, I use:
for each in `ls -1`;do du -sh $each;done
528M cache
39M lib
8.0K local
32K lock
262M log
16K lost+found
4.0K mail
and then cd and follow the big directories to the big files
[...] #335 Bash tips and tricks. Несколько полезных хитростей популярной в среде [...]
Jason, have a look at dutop.
Also baobab presents disk usage is a nice graphical way
Very nice tips.
Using ctrl-R to search history is way better than “cat .bash_history | grep foo” which I’ve been using.
I’ll definitely have to try some of these. I’ve been getting myself more and more comfortable in a shell. I find there are certain things I can do faster from the command line and certain things I still do faster from the GUI. But I’m learning.
Thanks.
Very useful article indeed. Thanks!
To refer to the last parameter in the previous command you can use $_
(a specific instance of an object)
Eg.
ls /tmp
echo $_ # prints /tmp
On a bash shell, you can navigate with these commands
* ALT f - one word forward
* ALT b - one word back
(in case you are typing a loooooong command)
* CTRL a - beginning of current command line
* CTRL e - end of the current line
Further, to toggle cases of the command/arguments,
* ALT l (it is eL small case) to change the next word to all smallcase letters
* ALT u to change the next word to all uppercase letters
* CTRL w deletes a word backwords (more like backspace, but for an entire word)
* CTRL k deletes the rest of the line after cursor
[...] read more | digg story [...]
Thanks for everyone’s comments - there’s more useful info in the comments than in the article now!
Great tips, thanks alot!
[...] Bradshaw posted some useful bash tips - making bash remember your history, making the shell forget your spelling mistakes, removing [...]
[...] Bash tips and tricks « Richard’s linux, web design and e-learning collection (tags: bash tips linux shell unix sysadmin commands) [...]
Maybe Maarten should reconsider Windowz.
How can you be using linux and avoid the terminal.
http://www.catb.org/~esr/writings/unix-koans/gui-programmer.html
VERY nice article (and comments!) for those trying to convert from the dark ways of the M$.
Richard, you wrote “make sure you use a normal ‘ not a ‘ - I’ve changed the text above to make it work properly now.”
I copied and pasted but I still get “bash: -a’: command not found” (also on an Ubuntu machine)
Richard, you wrote “make sure you use a normal ‘ not a ‘ - I’ve changed the text above to make it work properly now.”
I copied and pasted but I still get “bash: -a’: command not found” (also on an Ubuntu machine)
Doh - you are right. Just make sure you use real apostrophes then. After pasting it change both to a normal apostrophe - damn blog template!
Spot on …. that fixes it, thank you
I am using linux since last three years and history allawys annoyed me…thnaks for your tips, it did a great work for me
I have another good suggestion to improve your bash history control, i recommend to use it: Extended Bash History like in Gentoo
[...] Richards linux, web design and e-learning collection: Bash Tips and Tricks [...]
[...] Перевод заметки Bash tips and tricks [...]
[...] Источник заметки Оригинал на английском [...]
Re: Ecelis’ comment: “Just to pin point, bash is not the default shell on Ubuntu since 6.10″:
This is true, but also false. Gnome-terminal is the default terminal emulator, but by default it operates in a bash shell environment, and bash is part of the default install from 6.10 straight through to the current 7.10 (and before, and likely after, though the zsh lobby is still fairly strong on the Ubuntu forums, and I can see the advantages of zsh myself). I added most of these tips to my .bashrc, tweaked a few other settings, cranked up the terminal, and they all worked and applied. If you have a ~$ at your prompt, odds are you are running a bash shell in your terminal, too.
[...] a parting shot, I recommend reading Bash tips and tricks and 10 Linux shell tricks you don’t already know if you run Linux. Bookmark/Search this post [...]
Excellent stuff. Most all of these work with OS X as well.
If you don’t have a .bashrc file in the terminal, then it could be the .profile file instead. It was the case for me, and after adding the mods to it, they functioned just as they would if I were using linux.
If you are using multiple terminals and want to share the history between them as you are working, you should instead use:
PROMPT_COMMAND=’history -a && history -n’
You’ll need to press enter once before you get the history from the other bash shell(s) though.
Nice, thanks!
Very nice article indeed and superb comments, I am especially fond of Pavan’s contribution.
[...] Editing your .bashrc file so that you could keep your commands appended to the history instead of overwriting the history. What to write in .bashrc? This: [...]