Bash History Examples: Search, Re-Run and Edit Shell Command History

Last updated:
Table of Contents

These are some little tips and hacks you can use to enhance your productivity while working on bash.

It might seem a small contribution to justify learning yet another tool but, when put together, all these things will probably help you make more effective use of your time.

Search for command containing a string

Hit Ctrl + r:


Then start typing.

For example, if you type apache, you would probably see something like this (sudo /etc/init.d/apache2 restart was the last command I ran containing apache, that's why it show up first)

(reverse-i-search) `apache': sudo /etc/init.d/apache2 restart

To see the next matches, hit Ctrl+r again as many times as you want. When you find the command you want, hit tab so it'll be available for you to edit or run it.

ctrl-r-apache-restart Use Ctrl+r to search through your command
so you don't have to remember
every single command you use.

Re-run last command using sudo

If you get a permission denied-like error after running a command and you have access to sudo, do this to run the last command using super user privileges:

$ sudo !!

Re-run last command with replacement

(example using svn commands)

$ svn diff path/to/my/file.txt

After seeing the diff result, say you want to commit that very same file. Just replace "diff" with "commit" in the last command:

$ !!:gs/diff/commit/
svn commit path/to/my/file.txt

Set maximum history size

Set both variables to the maximum desired history size1

Storing all the commands you use takes up some space, naturally.

You can control how many lines you want to keep in the using HISTSIZE and HISTFILESIZE enviroment variables (put these in .bashrc to make it permanent)

# keep up to 100 thousand command lines in history
$ HISTSIZE=100000

1: This is an oversimplification. See this post by elixir_sinari on for more info.


Dialogue & Discussion