How to Use the History Command in Linux

The history command in a Linux terminal is a built-in shell utility that tracks, records, and displays a list of previously executed commands. This article explains how the history command works, how to navigate and search your terminal records, methods for re-executing past commands without retyping them, and how to manage or clear your command log to improve productivity and security.

What the History Command Does

Whenever you run a command in a Linux shell like Bash or Zsh, the shell appends that entry to an internal log. When you enter history into the terminal, it outputs a chronological, numbered list of these past commands. This allows users to review previous system changes, audit their workflows, or retrieve complex commands used earlier.

Viewing Command History

Running the command by itself displays the entire stored history:

history

Because this list can contain hundreds or thousands of lines, you can limit the output to the most recent entries by appending a number. For example, to view only the last 10 commands:

history 10

You can also pipe the output to a pager like less to scroll through the entries one screen at a time:

history | less

Re-executing Previous Commands

The history command integrates with event designators (the exclamation mark !) to quickly rerun commands without retyping them:

Searching Through History

Instead of scrolling through extensive lists, you can locate specific commands using two primary methods:

  1. Piping to Grep: Filter historical commands by keyword using standard text utilities:
    history | grep "ssh"
  2. Reverse Interactive Search: Press Ctrl + R in the terminal and begin typing any part of the command you want to locate. The shell displays matching commands interactively; press Enter to run the found command, or press Ctrl + R again to cycle backward through older matches.

Managing and Clearing History

By default, commands in the current session are stored in memory and written to a file in your home directory (such as ~/.bash_history) upon exiting the terminal. You can manage this file and your active session memory with specific flags:

Configuring History Behavior

You can customize how history operates by editing shell variables in your ~/.bashrc file. Key variables include: