Bash history essentials

I’ve been using the Bash history since a long time, but in a rather limited way. I’d use the “history” command, !<num> to execute command again, !* to get all parameters of the last command, and Ctrl-r to match previous commands.

This article by symkat showed me a lot more interesting history features.

Here’s my personal list of what a productive developer needs to know about Bash history:

  • history: Show the history in case you get lost.
  • !<num>: Execute line again, where is the number shown by history.
  • Ctrl-p: Browse the history backwards. Also on cursor-up, but doesn’t make you leave touch typing position.
  • Ctrl-r: Search backwards. Invaluable. Matches can anchor anywhere. Pressing it repeatedly shows older matches.
  • !$: Substitutes for the last word of the previous line. Very useful for doing something else with the same thing. For example, you might first say ls -R very/long/path, then du !$ to show the directory’s size.
  • Esc-. or Alt-. (that’s Alt-PERIOD): Like !$, but Bash inserts the word into your current line right away, so you can check or modify it.

Also, setting the HISTCONTROL environment variable to “Ignoreboth” to ignore duplicate history entries and commands starting with a space is a must.

How to quickly print certain lines of a huge file by number

If you have to work with huge text files, you know that most editors as well as less are very slow at jumping to a certain line in the latter part of a large file. Turns out that GNU sed is very good at it, although it will of course not replace an editor. For most people at least, those who write Tetris in sed will probably be fine.

$ wc -l uniprot_sprot.dat
31510440 uniprot_sprot.dat

$ time sed -n '30000000p' uniprot_sprot.dat
real    0m8.982s

$ time sed -n '29999900,30000000p' uniprot_sprot.dat
real    0m9.242s