Linux history Command: Review and Reuse Shell Command History

The history command in Bash shows previous commands remembered by the current shell along with their numbers and is used to search, re-execute, delete items, or synchronize with the history file. To view only the most recent few commands, use history 20; to search for a specific string, use history | grep 'search term'; and to quickly find commands while typing, use Ctrl+r.

history is a built-in command in Bash. The explanation in this article is based on Bash, and other shells like Zsh or Fish may have different history files and settings.

What is the history command?

Bash stores commands entered by the user in an interactive shell in a memory history list. history is a command that allows you to view and edit this list and read or write the history file indicated by HISTFILE.

The default history file is usually ~/.bash_history. When Bash starts, it reads this file to create the memory history list, and when the shell exits normally, it saves the current history to the file. Detailed behavior can be found in the GNU Bash History Facilities documentation.

Command history is a convenience feature, not a security audit log. Users can delete entries, and if the shell terminates abnormally or history recording is disabled, it may not be saved.

Basic Usage

Running without options will print the history of the current Bash session with numbers.

history

An example of the output is as follows.

  241  apt update
  242  systemctl status ssh
  243  journalctl -u ssh
  244  history

To view only a recent portion of the history, such as the last 20 entries, specify a number.

history 20
Format Function Points to Note
history n Display the last n entries It is based on the memory list of the current shell.
history -c Delete the entire current record list The state of other shell sessions and files should be considered separately.
history -d number Delete the specified item First, check if the number to delete is correct.
history -a Add new items from this session to the end of the file HISTFILE must be set.
history -n Add new entries from the file to the current list Useful when importing records added in another session.
history -r Add the entire history file to the current list May duplicate entries that already exist.
history -w Overwrite the history file with the current list If multiple terminals are open, it may affect the history of other sessions.
history -p expression Print only the results of history expansion It is useful for checking the expanded result of ! before execution.
history -s command Add to history without executing the command It goes in as the last entry of the current history list.

For the exact definitions and return statuses of each option, refer to the GNU Bash History Builtins documentation.

Searching previous commands

Filtering the list with grep

If you want to see only the lines in the history that contain a specific string, use grep together with a pipe.

history | grep 'systemctl'

To ignore case, use grep -i.

history | grep -i 'nginx'

This method is convenient for checking results, but the current search command included in the output may also appear in the results.

Searching while typing with Ctrl+r

If Bash is using the basic Emacs editing mode, you can perform a reverse incremental search of previous commands with Ctrl+r. Each time you type a character to search, the most recent matching entry is displayed, and pressing Ctrl+r again moves to the next older result.

  • Enter: Executes the displayed command.
  • Left/Right arrow keys: Finish the search and edit the command.
  • Ctrl+g: Cancels the search and returns to the original input.

It is safe practice to end the search using the arrow keys just before execution to review the command and its arguments. The search method is explained in the GNU Readline documentation on searching the command history.

Re-execute Previous Command

History Expansion Using Exclamation Marks

In interactive Bash, you can use history expansion starting with ! to recall previous commands.

Expression Meaning Example
!! Previous Command sudo!! adds sudo in front of the previous command.
!125 Command with history number 125 You can check the number from the history output.
!-3 The third previous command from the current position Select recent commands by relative position.
!ssh The most recent command starting with ssh If there are many commands with the same prefix, an unexpected item may be selected.
!?nginx? The most recent command containing nginx Search by a string in the middle of the command.
^old^new^ Replace the first matching string of the previous command and execute It is used to correct short typos and execute again.

History expansion is enabled by default in interactive Bash, but it is not performed by default in non-interactive shell scripts. For detailed syntax, refer to the GNU Bash History Expansion documentation.

Check the expansion result before executing

!number and !string can execute the found command immediately, so be especially careful if there are delete, permission change, or system shutdown commands in the history. If you pass the expression to history -p in quotes, you can check the expansion result without executing it.

history -p '!!'
history -p '!ssh'

In Bash using Readline, setting the following option allows the history expansion result to be displayed in the editing buffer first without immediate execution.

shopt -s histverify

In multiple terminal environments where numbers can change easily, it is often safer to search with Ctrl+r, check the content, and then execute.

Delete command history

Delete a Specific Entry

First, check the number with history and then delete the corresponding entry from the memory's history list using the -d option.

history -d 125

If the current Bash supports range deletion, you can also specify a start and end number.

history -d 120-125

To reflect the deletion results in the current history file, you can check the list and then run history -w. However, be aware that other terminal sessions might later write the previous history back to the file upon their exit, so make sure multiple sessions are not open.

Delete the Entire Current List

The -c option clears all the entries in the history list in the current shell's memory.

history -c

To update the history file to match the current list, you should understand how history -w works before using it. History deletion only targets the shell history and does not remove system logs, audit logs, backups, or history from other terminals.

History File and Multiple Terminal Sessions

Bash has a separate memory history list for each running shell. By default, commands just executed in another terminal may not immediately appear in the history of the current terminal.

Command Behavior between the history file and the current session
history -a Appends new history from the current session that has not yet been saved to the file to the end of the file.
history -n Adds new lines from the history file that the current session has not yet read to the memory list.
history -r Appends the entire contents of the history file to the end of the current memory list.
history -w Overwrites the history file with the entire current memory list.

To bring in new history from another terminal, first add it to the file in that terminal with history -a, then read it in the current terminal with history -n.

history -a
history -n

You can use the histappend option to add new entries instead of overwriting the history file when the shell exits.

shopt -s histappend

To continue using this setting, add it to the user's ~/.bashrc. There is also a way to set PROMPT_COMMAND to automatically synchronize at each prompt from multiple terminals, but you should not overwrite it without checking the current value, as existing settings or programs may be using this variable.

History-related environment variable settings

Variable Role
HISTFILE The path to the file where the history is stored. The common default value is ~/.bash_history.
HISTSIZE The maximum number of commands to keep in the current shell's memory history list.
HISTFILESIZE Limits the maximum size of the history file in terms of lines.
HISTCONTROL Set storage rules, such as not recording commands that start with a space or consecutive duplicate commands.
HISTIGNORE Specify command patterns to exclude from recording, separated by colons.
HISTTIMEFORMAT Specify the date and time format to display in the history output.

For example, the following settings maintain 5,000 entries in memory and 10,000 entries in the history file, reduce commands that start with a space and duplicate commands, and display date and time.

HISTSIZE=5000
HISTFILESIZE=10000
HISTCONTROL=ignoreboth:erasedups
HISTTIMEFORMAT='%F %T '
shopt -s histappend

To apply continuously, add the above settings to ~/.bashrc, then start a new Bash session or reload the configuration file.

source ~/.bashrc

HISTCONTROL=ignoreboth applies both ignorespace and ignoredups. erasedups removes previous entries identical to new commands from the history list. Detailed rules for each variable can be found in the GNU Bash Variables documentation.

Command history and security

If you enter passwords, API keys, tokens, or private key content as command-line arguments, they can be exposed not only in shell history but also in running process information or other logs. For sensitive information, it is recommended not to enter it directly on the command line but to use standard input provided by the program, a secure credential store, or a configuration file with restricted access.

If ignorespace is set in HISTCONTROL, commands that start with a space can be excluded from the history. However, you need to depend on whether this setting is actually active, and it does not prevent other logs, so it should not be relied on solely as a method for protecting sensitive information.

printf '%s\n' "$HISTCONTROL"
printf '%s\n' "$HISTFILE"

Even if you delete entries with history -d or history -c, the same information may remain in other shell sessions, backups, audit logs, and application logs. If credentials are exposed, do not just delete the history; you should invalidate the affected password or token and issue a new one.

Common issues

The latest commands from another terminal are not visible

Each Bash session uses an independent memory list. After executing history -a in the terminal where the commands were run, try executing history -n in the terminal you want to check. In the long term, you can review histappend and shell initialization settings.

History disappeared after closing the terminal

HISTFILE may be empty or you may not have permission to write to the history file, or HISTSIZE and HISTFILESIZE may not be set to 0. If the shell was forcibly terminated, the process of saving the history at exit may not have been performed.

The history numbers have changed from before.

History numbers are not fixed identifiers but the position in the current memory list. If you delete entries or reload the file to merge history from another session, the numbers can change. It is safer to search and check the command content rather than remembering and executing old numbers.

Can the same settings be used in Zsh or Fish?

They cannot be applied as-is. Even if there is a feature named history, the history file and the way it syncs with environment variables differ for each shell. First, check printf '%s\n' "$SHELL" and the official documentation of your current shell.

Summary

history in Bash can be used not only to view previous commands but also to delete specific entries, read/write the history file, and synchronize between sessions. For everyday searching, history | grep and Ctrl+r are convenient, and when re-executing using history expansion, it is necessary to first check the command content.

To change the amount and storage method of records, review HISTSIZE, HISTFILESIZE, HISTCONTROL, HISTTIMEFORMAT, and histappend together. The purposes of other commands can be found by task in the list of Linux commands.

More in This Category
Linux ss Command: Inspect Open Ports and Sockets

Linux ss Command: Inspect Open Ports and Sockets

Learn how to inspect Open Ports and Sockets with the Linux ss command, including practical examples, key options, and important precautions.

Linux parted Command: Inspect and Manage Partitions

Linux parted Command: Inspect and Manage Partitions

Learn how to inspect and Manage Partitions with the Linux parted command, including practical examples, key options, and important precautions.

Linux pkill Command: Signal Processes by Name

Linux pkill Command: Signal Processes by Name

Learn how to signal Processes by Name with the Linux pkill command, including practical examples, key options, and important precautions.

Linux dd Command: Copy and Convert Data by Blocks

Linux dd Command: Copy and Convert Data by Blocks

Learn how to copy and convert files or block devices with Linux dd, choose block sizes and ranges, display progress, verify results, and avoid overwriting the wrong device.

Linux diff Command: Compare Text Files and Directories

Linux diff Command: Compare Text Files and Directories

Learn how Linux diff compares text files and directories, produces unified patches, ignores selected whitespace changes, and reports differences through exit status.

Linux fdisk Command: Inspect and Edit Disk Partitions

Linux fdisk Command: Inspect and Edit Disk Partitions

Learn how to inspect and Edit Disk Partitions with the Linux fdisk command, including practical examples, key options, and important precautions.

Linux tree Command: Display a Directory Tree

Linux tree Command: Display a Directory Tree

Learn how to use the Linux tree command to display directory contents as a readable hierarchy and control depth and filtering, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux alias Command: Create Command Shortcuts

Linux alias Command: Create Command Shortcuts

Learn how to use the Linux alias command to create, inspect, and make shell command aliases persistent, with essential options, practical examples, output interpretation, and common troubleshooting tips.

Linux cmp Command: Compare Files Byte by Byte

Linux cmp Command: Compare Files Byte by Byte

Learn how Linux cmp compares two files byte by byte, reports the first mismatch, runs silently in scripts, limits ranges, and differs from diff and checksums.

Linux cat Command: Display and Concatenate File Contents

Linux cat Command: Display and Concatenate File Contents

Learn how to use the Linux cat command to display text files, concatenate multiple files, number lines, reveal hidden characters, and avoid unsafe redirection mistakes.