Bash History: Search, Re-Run and Edit Shell Command History
Last updated:- Search for command containing a string
- Re-run last command using sudo
- Re-run last command with replacement
- Set maximum history size
- Update history across tabs
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
:
(reverse-i-search)`':
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.
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
Use $!!gs/replacethis/withthis
Example: You just ran $ svn diff path/to/my/file.txt
and you want to run svn commit
with that same file:
Replace "diff"
with "commit"
in the last command:
$ svn diff path/to/my/file.txt
$ !!: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)
# add this to .bashrc
# keep up to 100,000 command lines in history
HISTSIZE=100000
HISTFILESIZE=100000
Update history across tabs
This will make it so that commands that you type in one terminal tab are immediately available when you access the history in other tabs
# add this to .bashrc
# make new commands get appended to history
shopt -s histappend
# immediately add the command to the history, and
# always reload the new commands from history
PROMPT_COMMAND="history -a;history -n;$PROMPT_COMMAND"
1: This is an oversimplification. See this post by elixir_sinari on Unix.com for more info.