History Lesson

Command Line – Bash History

© Lead Image © Scott Rothstein, 123RF.com

© Lead Image © Scott Rothstein, 123RF.com

Article from Issue 214/2018
Author(s):

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).

Figure 1: The bare history command lists the contents of the history file.

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.

Figure 2: You can specify the number of history items to list after the bare command. Shown here are two listings, one for showing 3 entries and another for 4.

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.

Figure 3: Some event designators work without requiring the history command.

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 of ignboth 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 by HISTLSWORDS, 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 contains apt-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 to  .
  • HISTFILE 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

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • Command Line: Customizing Bash

    Ease into your comfort zone with these tips for customizing Bash.

  • Bash Tricks

    The Bash shell is powerful and infinitely expressive. In this article we describe some tricky techniques you can use to enhance and customize your Bash environment.

  • Introducing Bash

    Beyond all the splash screens, screen savers, and vivid rock-star wallpaper is the simple yet powerful Bash shell.

  • Bash History on Steroids

    You can always browse the Bash history using your arrow keys, but Bash's search capabilities are very limited. Enter the clever Bash History Suggest Box.

  • Command Line: Fish

    The fish shell provides many features that rival the well-known Bash. We examine some highlights.

comments powered by Disqus

Direct Download

Read full article as PDF:

Price $2.95

News