Control Bash History

Pavel Saman
2 min readJun 16, 2022

--

Controlling bash history has always been important to me because I can be much more efficient when I set it in a certain way. There’re five variables I know of that can help with that, let’s see what they are.

First things first. I keep bash variables in one file ~/.bash_exports. Then I source the file like so in ~/.bashrc:

[[ -f ~/.bash_exports ]] && . ~/.bash_exports

Separation is a good habit, it pays off to keep things clean and in order.

However, let’s see the variables. There’re these five variables I know of:

export HISTSIZE=1000
export HISTFILESIZE=3000
export HISTCONTROL=ignoreboth:erasedups
export HISTIGNORE="history"
export HISTTIMEFORMAT="%F %T "

Obviously the values can change, this is what I currently use. Let’s see what it means:

  • HISTSIZE and HISTFILESIZE control how many history entries there will be
  • HISTCONTROL gives you control over what gets stored in history; ignorespace will ignore commands that start with a space, ignoredups will not store duplicate if a command is the same as the immediate previous command, ignoreboth is a combination of the previous two values, and erasedups causes all previous lines matching the current line to be removed from the history list before that line is saved
  • HISTIGNORE means that commands in this list (separated by a colon) will not be included in history
  • HISTTIMEFORMAT means that time information can be stored alongside commands in history; the time is saved in ~/.bash_history on lines starting with # and is displayed in a format specified in this variable when using $ history command

Then I also recommend reading the man page on history command. It includes some useful shortcuts that can save some time.

For example:

$ !grep

will run the most recent command preceding the current position in the history starting with the string grep.

$ !-1

will run the current command minus one.

Or this:

$ !!

will run the previous command. This can be useful when you run a command that required sudo privileges without using sudo. You will get an error, so you can just type:

$ sudo !!

to run the command again with sudo. It can save some time.

There’s for sure more to it, but you can always explore the man pages. I usually don’t need more than setting the variables, which I usually do only once in a while when I’m on a new machine.

--

--

No responses yet