History Lesson
Command Line – Bash History
You can do more with the Bash history command than just using the arrow keys. We show you how to use this command-line tool more efficiently.
If you use the command line regularly, you probably use the Bash history file. Usually located in ~/.bash_history
, the history file stores hundreds of previous shell commands, enabling you to reuse them without typing them. If you are like most users, your use of Bash history is largely confined to using the arrow keys to scroll back one or two commands. Yet the history
command itself offers dozens of ways to search and reuse the history more efficiently: the regular command options, history expansions, environment variables, and a couple of alternative search commands as well.
The limited use of Bash history may now be common partly because many users today have little command-line experience. Even more importantly, the information available in the history
command's man and info pages is verbose and only partial [1]. At best, users pick up isolated tips from how-to articles, which give them little sense of the command as a whole.
Still another reason for not making full use of the history
command is the uncertainty about all it can do. For one thing, the command is controlled by several automatically installed environmental variables that users may never see unless they open ~/.bashrc
. For another thing, by default, the file collects every entry at the command line, whether the entry is properly formed or not. Additionally, entries from every terminal opened after the first terminal are not collected, but not written, which means the history of all except the original terminal are lost when the window is closed. Such quirks are logical, but arcane enough that it quickly makes the history
command a mystery to the average user. What follows is an attempt to systematically explain the different ways you can use history more exactly.
The Basic Command and Its Options
Issuing the basic history
command displays all the commands in the history file one per line. Probably, you will want to pipe it through less
, especially if your interest is in the most recent commands, which are listed at the top of the file. Each line begins with the line number in the history file. The displayed information helps you locate commands to reuse, so, essentially, the unmodified command is a search feature (Figure 1).
Very quickly, you are likely to want to add an option. These options, you will notice, have changed so little since the days when Unix ruled that they are prefaced by a single hyphen and do not have the corresponding GNU-invented options that start with two hyphens.
Most of the options for the history
command are housekeeping options. For example, you can use -dNUMBER
to delete a specific entry for which you have no use for one reason or another. If your history is long and you see no use for most of the entries, you can even clear the entire history file with -c
. Perhaps most importantly, if you want to reuse recent entries before the next time you log in, you can add them immediately with the -a
option. To avoid duplications, you could use -n
instead and only add commands from the current session that are not already in the history file. None of these options give any feedback when errors occur, so be certain you know what you are doing when applying them.
History Expansions
In addition to the options found in most commands, history
also has what the man page describes as history expressions. History expressions can be thought of as the regular expressions of the history
command that draw on the history file, but not always with the need to type history
. They fall into three categories: event designators, word designators, and modifiers.
Event designators pinpoint an entry in the history file and begin with an exclamation mark (!). For example, if you have identified the line of the command you want to repeat, you can add !NUMBER
to the basic command, while !-NUMBER
selects a number of lines before the current one (Figure 2). Two exclamations points (!!) will repeat the previous command. More elaborately, !COMMAND
will let you to reuse the last time the specifically named command was used. If you know the number for a specific command, you can reissue it by adding !NUMBER
– all of which is usually considerably faster than scrolling with the arrow keys.
At other times, you might notice a command that was incorrectly entered, such as sl
for ls
. If it was the last command, you can save yourself some typing and add COMMAND !*
to enter the proper spelling while using the same options and file paths (Figure 3). In other cases, an event designator works with a string of characters, so !STRING
locates the most recent entry with the specified string. If, in the middle of typing, you realize that you have recently used the same command that you are inputting, !#
will complete it with the last matching entry.
Word designators filter by character strings, with the position of words counted from the beginning of the line, the first word being
and the last word a number or $
. Multiple words are separated by single spaces.
After a word designator, various modifiers can be added, each prefaced by a colon (:). An h
will reproduce only a file name extension, and a t
will remove it. The modifier s/OLD/NEW
will allow you to edit an entry when you renew it. If you have made a substitution in the previous entry, &
will repeat it. Such expansions can get confusing, so you may want to add p
, so that the modified command is displayed, but not carried out.
These are only some of the most common history expansions available. For a complete list, consult the man or info page [1], both of which focus on history expansions to the exclusion of the rest of the history
command's complexity. However, even the examples given are enough to show how much more there is to the command than scrolling with the arrow keys.
Environment Variables
Some aspects of the history
command and file are set either temporarily or permanently with environmental variables. To set the variables for the current session, use the export
command before using history
. To set the variables permanently, use the env
command. Permanently stored variables are saved to a user's .bashrc
file, and variables for the entire system to /etc/bashrc
. The history variables for the session can be overwritten using the command:
unset export VARIABLE=setting
Permanent variables can be overwritten by entering a new value.
Five history variables are supported:
HISTCONTROL=SETTING
can be completed in several ways, all of which are designed to prevent duplicates. The choice ofignboth
prevents the history file from writing a command that is already present in the file. By contrast,ignorespace
will not write a command to the file that starts with a blank space. If duplicates already exist, you can remove them with
export HISTCONTROL=erasedups
HISTCONTROL
may be supplemented byHISTLSWORDS
, a colon-separated list of character strings that indicate which commands the history file should not store. For instance, since package installation is often a one-time operation, some users might ban the storage of any file that containsapt-get
.HISTIMEFORMAT
displays the time a command in the history was issued, giving you another means to locate it. The variable uses the standard format for date and time:%d
for the day,%m
for the month,%yyyy
for the year, and so on.HISTSIZE
is the number of entries stored at one time, 500 is usual in most distributions. When the number of entries is exceeded, the oldest entries are overwritten. Since memory is cheap these days, many history users set a much higher number for convenience. At the opposite end of the scale, you can turn off the history file by setting this variable toHISTFILE
designates a file other than.bash_history
for storing entries.HISTFILE
is mostly useful for a common history file between different users or systems, although moving from the default may make the whole idea of history less useful.
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
Fedora 41 Beta Available with Some Interesting Additions
If you're a Fedora fan, you'll be excited to hear the beta version of the latest release is now available for testing and includes plenty of updates.
-
AlmaLinux Unveils New Hardware Certification Process
The AlmaLinux Hardware Certification Program run by the Certification Special Interest Group (SIG) aims to ensure seamless compatibility between AlmaLinux and a wide range of hardware configurations.
-
Wind River Introduces eLxr Pro Linux Solution
eLxr Pro offers an end-to-end Linux solution backed by expert commercial support.
-
Juno Tab 3 Launches with Ubuntu 24.04
Anyone looking for a full-blown Linux tablet need look no further. Juno has released the Tab 3.
-
New KDE Slimbook Plasma Available for Preorder
Powered by an AMD Ryzen CPU, the latest KDE Slimbook laptop is powerful enough for local AI tasks.
-
Rhino Linux Announces Latest "Quick Update"
If you prefer your Linux distribution to be of the rolling type, Rhino Linux delivers a beautiful and reliable experience.
-
Plasma Desktop Will Soon Ask for Donations
The next iteration of Plasma has reached the soft feature freeze for the 6.2 version and includes a feature that could be divisive.
-
Linux Market Share Hits New High
For the first time, the Linux market share has reached a new high for desktops, and the trend looks like it will continue.
-
LibreOffice 24.8 Delivers New Features
LibreOffice is often considered the de facto standard office suite for the Linux operating system.
-
Deepin 23 Offers Wayland Support and New AI Tool
Deepin has been considered one of the most beautiful desktop operating systems for a long time and the arrival of version 23 has bolstered that reputation.