Linux: Bash Scripting: Search Bash History
Often when at the linux terminal I need a long command that I recently tapped out so naturally I use the up/down arrow keys to look through my recently typed in commands. But if I’m searching for a command I used days ago then I’ll be pressing the up/down arrow keys a lot just to find this one bash command.
The easiest way to speed this process up is to search your bash history like so:
cat ~/.bash_history | grep -i searchstring
Where searchstring represents the command or piece of text to search for. And that’s it. Of course remembering that command and typing it out may take some time too so, as with most macro/helper scripts, it is best to stick it in a file of its own. I’d suggest creating a folder in your home called scripts:
mkdir ~/scripts
And then opening your favourite text editor and creating ~/scripts/shist:
#!/bin/bash
cat ~/.bash_history | grep $@
The $@ means is where the passed paramaters are placed - in this case its our search string (or regular expression and other paramaters if we’re feeling so inclined), and so we execute this command by typing:
shist searchstring
Don’t do that yet of course because we haven’t finished. First we need to make the script executable:
chmod +x ~/scripts/shist
And then finally we need to put the scripts directory into the path - so edit your ~/.bashrc file and find the line where it says:
export path= blah blah blah
and append the following to that line:
:~/scripts
and that should be it. What would be nice is if each line of output was numbered and put into environment variables so you could access them easily… hmm, I sense another script coming on…
Related posts
Convert .deb package from i386 to lpia
lpia x86 debian packages
USB & CD Custsomisation (Windows)
How to execute Javascript (and Google Adsense) in AJAX
Leave a Reply