Controlling the History and Setting the Shell Editor

Learn how to control what commands are stored in the history.

Controlling the history

We can control which commands get stored in the history and how many entries are preserved in the current session and across all sessions, all through a handful of shell variables. Let’s add some to our .bashrc file.

The HISTCONTROL variable lets us ignore commands that start with a space. This can be really useful to hide commands containing sensitive information from our history. It’s often a default setting.

The HISTCONTROL variable also lets us ignore repeated duplicates. So, if we type ls three times in a row, we can have it saved only once. This only checks the previous command for duplicates, but it’s still a nice way to trim down the history a bit.

We can set one or both of these options like this:

HISTCONTROL=ignorespace:ignoredups

Better yet, to set both options, we can use the ignoreboth value instead:

HISTCONTROL=ignoreboth

If we want duplicates to go away entirely, we add erasedups:

HISTCONTROL=ignoreboth:erasedups

This removes all previous instances of commands we’ve typed, only keeping the most recent command. We don’t recommend this approach because it makes it more difficult to see the actual linear history of commands. History is saved to a file when we exit our session. If we want to append to the history file instead of starting with a fresh one each time we open our shell, we add this line to our configuration:

shopt -s histappend

We can control the size of the history file. We add these lines to control the number of history lines saved in our current session (HISTSIZE) and how many lines we save in the file (HISTFILESIZE) when we exit our shell:

HISTSIZE=1000
HISTFILESIZE=2000

Finally, if there are commands we’d like the history command to ignore, we add them to the HISTIGNORE command. For example, to stop recording exit and clear commands, we add this line:

HISTIGNORE="exit:clear"

This keeps our history cleaner. We need to be careful with what we ignore here too, especially if we want to use our history as a log of our session.

Run the complete code on the terminal below for practice.

echo "# START:return
[ -z "$PS1" ] && return
# END:return

# START:histcontrol
HISTCONTROL=ignoreboth
# END:histcontrol

# START:histappend
shopt -s histappend
# END:histappend

# START:histsize
HISTSIZE=1000
HISTFILESIZE=2000
# END:histsize

# START:histignore
HISTIGNORE="exit:clear"
# END:histignore" > ~/.bashrc
cat ~/.bashrc

Get hands-on with 1400+ tech skills courses.