Linux Tips - Making the most of the History command
The Linux history command will show you hundreds, if not thousands, of the commands you've previously typed into the terminal. If you find this creepy and want to do something about it, the entirety of it is stored in ~/.bash_history. Use your favorite text editor to delete individual lines from it or clear the whole thing with the following command:
cat /dev/null > ~/.bash_history
What does that do? cat /dev/null displays the contents of /dev/null, which are...absolutely nothing. /dev/null is a fake device that accepts any kind of input you send it and discards it, or it will send you complete emptiness. > takes the emptiness we get from /dev/null and says, ""write it to a file."" In this case, the file is ~/.bash_history. So, in essence, we are getting a bunch of nothing from /dev/null, and overwriting the contents of .bash_history with that nothing. But that's not the point of this article. Recalling Individual Items You can recall individual items in order of entry from your history just by pressing the up and down arrows while at a prompt. View Entire History To view your full history (or as much as your buffer will allow), use the history command. View Only Some History To view just a subset of that history, say, the last 10 commands, use history 10. Find A Certain Command in History Ran a command successfully and then forgot the syntax later on?
history | grep -i xoxoxo
With that, we're piping your entire history to grep, which searches through it for hits containing the word ""xoxoxo"" in this case. Change ""xoxoxo"" to the term you're looking for-- the -i flag makes capitalization not matter. Re-Run the Last Command This is an odd one:
Yes, two exclamation points will re-run the last command. Run a Command from History See those numbers next to each command? You probably guessed there must be a way to recall those commands by number rather than retyping them, and you guessed right. If you want to re-run command 1549, it's very simple:
Hopefully this serves as a neat reference for some tricks you can do with the history command to be a little more efficient at the command line!
If you would like additional training in Linux, do check out our course offerings!