Linux Bash History: A Comprehensive Guide

By
Sara Zivanov
Published:
October 30, 2025
Topics:

In Linux, the Bash history feature records all executed commands in a list that users can review, reuse, or modify. It is one of the most practical tools that improves efficiency in the command line.

When you understand how Bash history works, you are able to manage stored commands, automate frequent tasks, and maintain more secure shell sessions.

This guide will explain what Bash history is, where it's stored, and how to view, edit, clear, or configure it with various methods and shortcuts.

Linux Bash History: A Comprehensive Guide

What Is Bash History?

Bash history automatically records all commands entered in the shell. It helps developers, system administrators, and users track their work, recall complex commands, and analyze their command-line activity for troubleshooting or optimization.

The recorded commands are stored in memory during the session and saved to a file, which gives users access to their command history across sessions.

There are multiple ways to view and interact with this history, including a text editor to inspect the saved file. For instance, when you open theย .bash_historyย fileย with aย text editor, such as Nano, Vim, or Emacs, you have an option to review past sessions, copy frequently used commands into scripts, or audit activity for security purposes.

Other ways, such as the history command, as well as its shortcuts, designators, and modifiers, offer different ways to access and manipulate Bash history.

Where Is Bash History Stored?

Bash stores command history in a hidden file in the user's home directory. By default, this file is named .bash_history. Each new session appends commands to this file when the shell exits, which ensures a persistent record across logins.

One way to open .bash_history is to use a text editor to view or manually edit previous commands.

Scripts can also access the file automatically without user interaction. For example, system administrators use scripts to analyze command usage patterns, identify frequently run commands, or audit a user's session for troubleshooting or security purposes.

Environment variables also determine the exact history file location. For instance:

  • HISTFILE. Tells Bash where to save the command history. By default, it points to .bash_history.
  • HISTSIZE. Defines the number of commands kept in memory during the current session. Once this limit is reached, older commands are removed from the session history.
  • HISTFILESIZE. Specifies the maximum number of commands stored in the history file. Older commands are discarded when the file exceeds this limit.

These variables allow users to keep more or fewer commands and control how long history is preserved across sessions.

Bash History Syntax

The basic history command syntax is:

history
Terminal output for history

The command prints a numbered list of all commands stored in the session's memory. The most recent commands appear at the bottom of the list.

Bash also supports history expansion operators, designators, and modifiers that extend the command's capabilities.

The history command also accepts several options for advanced control, although their use is not required for basic functionality.

Bash History Options

The history command includes several options that modify how the command history is displayed. The following table shows common history options:

OptionDescription
-cClears the entire command history from the current session.
-d [offset]Deletes the command entry at the specified position in the history list.
-aAppends new session commands to the history file.
-nReads and adds commands from the history file that have not yet been read by the current session.
-rReads the history file contents and adds them to the current session's history list.
-wWrites the current session's command history to the history file, which overwrites the existing content.
-pDisplays history expansion results without executing the expanded command.
-sAdds a command to the history list without executing it.

Working with Bash History 

Working with Bash history helps review past actions, rerun frequently used commands, or analyze activity. Proper command history management also enhances security and makes Bash more predictable across sessions.

The following sections explain how to view, modify, and control command history with practical examples and configuration options.

See Bash History 

The history command lists all commands executed in the current Bash session. Each entry is numbered, which makes it easy to reference specific commands later.

To view your full session history, run:

history

Another option is to limit the output to the most recent entries. For example, to display the last ten commands:

history 10
Terminal output for history 10

Bash also saves commands persistently in the .bash_history file in the user's home directory. When you open this file with a text editor, it allows you to:

  • Review commands from previous sessions.
  • Copy frequently used commands for reuse or automation scripts.
  • Search for commands by keyword or pattern.
  • Audit activity for troubleshooting, debugging, or security purposes.

To open or search this file with, for example, Nano, run:

nano ~/.bash_history
nano ~/.bash_history terminal output

This method allows you to review commands from previous sessions, copy frequently used commands, or audit past activity. Different keyboard shortcuts allow you to locate and review past operations.

You can also copy command blocks directly from the file into scripts or documentation with the standard copy/paste methods of your editor of choice. This is useful when you want to reuse sequences of commands without retyping, create automation scripts, or document processes.

Execute Command from Bash History 

Bash supports history expansion operators, which are separate from the history command itself. They let users quickly reuse previous commands without retyping them.

Expansion operators begin with an exclamation mark (!) followed by a reference to a previous command. For instance, the !! operator repeats the last executed command:

!!
!! terminal output

This shortcut immediately reruns the previous command, which is useful for repeated operations such as package installations or file edits. In this case, it repeats sudo apt update.

To execute a command by its number from the history list, run ! followed by the command number:

!25
!25 terminal output

This command reruns the entry numbered 25 in the history output. In this example, it re-executes the tar command.

Use ! with a specific string to run the most recent command that begins with that specified string:

!touch
!touch terminal output

This command re-executes the most recent touch command.

If the referenced command number or prefix does not exist in the current session's history buffer, Bash displays an error message that indicates no match was found.

For example, check whether wget was used in the current session with:

!wget
!wget terminal output

Add Timestamps to Bash History

By default, Bash history shows only command numbers and the commands themselves. To record when each command was executed, enable timestamps by setting the HISTTIMEFORMAT environment variable that tracks command execution times.

Set the variable in your current session with:

export HISTTIMEFORMAT="%F %T "

The format specifiers follow the same syntax as the date command:

  • %F. Displays the date (year, month, and day).
  • %T. Displays the time (hour, minute, and second).

The command has no output. Run history again to confirm timestamps now appear before each entry.

Date and time shown in the history terminal output

You can also customize the output. For instance, format the command to show only the time with:

export HISTTIMEFORMAT="%T "
Terminal output for time shown in the history command

To make this setting permanent, add the export command to your ~/.bashrc or /etc/bash.bashrc file with these steps:

1. Open the ~/.bashrc file in a text editor:

nano ~/.bashrc

2. Scroll to the end of the file and add this line:

export HISTTIMEFORMAT="%F %T "
Make settings permanent terminal output

3. Save and close the file.

4. Reload the configuration so changes take effect immediately:

source ~/.bashrc

The timestamps appear automatically in every new shell session once the configuration is reloaded.

To remove timestamps from Bash history and return to the default (no date/time) output, run the following and test with history:

unset HISTTIMEFORMAT
remove timestamps from Bash history terminal output

This only works if you used the command temporarily in your current terminal. However, if you changed your ~/.bashrc file, remove or comment out the added line. Next, reload your configuration.

Search Bash History

Bash provides several methods to search previous commands directly from the terminal without displaying the entire history list. These shortcuts make it faster to locate and re-execute past commands:

  • Search in reverse (Ctrl+R). Hit the key combination and begin typing a command. Bash dynamically searches backward through the command history. Use:
    • Ctrl+R repeatedly to cycle through earlier matches.
    • Enter to execute the found command.
    • Right Arrow key to edit the command before running.
Reverse Search terminal output
  • Search forward (Ctrl+S). Use Ctrl+S to continue the search in the opposite direction, moving toward newer commands. This feature is often disabled by default because it conflicts with terminal flow control. Enable it with:
 <span style="background-color: initial; font-family: inherit; font-size: inherit;">stty -ixon</span>
  • Browse previous commands. Use the Up Arrow and Down Arrow keys to cycle through the full command history one line at a time. This retrieves commands in reverse chronological order. It's useful when you need to quickly reuse or edit commands you've recently executed.
  • Search based on a pattern. Use the history command with grep to locate commands that match a specific string. For example, to display only previous tar commands:
history | grep tar 

All the search methods access the same shared history buffer, which ensures consistent results regardless of which approach you use.

Save and Sync History Across Sessions

By default, Bash saves the command history only when a session ends.

If multiple terminal windows are open, each maintains a separate in-memory history that overwrites entries when closed. Adjust several environment variables to synchronize and preserve command history more reliably.

Use the shopt (shell options) command to modify Bash runtime behaviors and how it manages history. To ensure commands from all sessions are saved rather than overwritten, enable the histappend option. Run the following:

shopt -s histappend

The command has no output but tells Bash to append new commands to the existing .bash_history file rather than to overwrite it. Add the line to your ~/.bashrc file to make it permanent.

To update the history file in real time, set the PROMPT_COMMAND variable to write new commands before each prompt. To do it, add the following line to your ~/.bashrc file:

export PROMPT_COMMAND='history -a'
update the history file in real time terminal output

This approach makes every executed command immediately appended to .bash_history, which allows multiple open sessions to share and update the same file.

If you often work in several terminal windows, run the following command in any active session to load new entries added by other sessions:

history -n

The command has no output but updates the in-memory history with all commands recently written to .bash_history. It keeps multiple sessions synchronized. Run this command before you start new work if other terminals were active earlier.

Clear Bash History

To remove outdated, sensitive, or unnecessary commands from your session or the history file, use one of the ways to clear Bash history. The method depends on whether you want to clear only the current session or remove the saved history file entirely.

To clear the current session's history, use:

history -c

This command empties the in-memory history buffer for the session. Previously executed commands in that session are no longer accessible via the history command or keyboard navigation.

However, this does not affect the .bash_history file until the session ends or you manually overwrite it. To remove the saved history file, run:

rm ~/.bash_history

This deletes the .bash_history file in your home directory, which permanently erases all stored commands.

Warning: Use with caution, as this action cannot be undone without a backup.

For a safe approach, combine both methods:

1. Back up the history with cp in a separate text file:

cp ~/.bash_history ~/history_backup.txt

2. Clear the session and remove the file:

history -c
rm ~/.bash_history

Configure Bash History

Bash's history behavior can be customized by environment variables in the ~/.bashrc file. These settings control how many commands are stored, how duplicates are handled, and which commands are excluded from history.

To configure these options permanently, add the following lines to your ~/.bashrc file:

export HISTSIZE=5000
export HISTFILESIZE=10000
export HISTCONTROL=ignoredups:ignorespace
export HISTIGNORE="ls:cd:pwd"
Configuring Bash history in Nano terminal output

The environment variables are:

  • HISTSIZE. Sets the number of commands retained in memory per session.
  • HISTFILESIZE. Defines how many commands are saved in the .bash_history file.
  • HISTCONTROL. Adjusts how Bash handles duplicate commands or commands that start with a space. The common values are ignoredups (skip duplicates) and ignorespace (ignore commands that start with a space).
  • HISTIGNORE. Specifies patterns of commands to exclude from history. Separate multiple patterns with colons.

The ~/.bashrc file is also used to make other Bash settings permanent, such as to enable timestamps or prevent command overwrites with options like HISTTIMEFORMAT and histappend.

After the file update, apply the changes with:

source ~/.bashrc

This ensures the new configuration takes effect immediately.

Exclude Commands from Bash History

Bash allows you to prevent specific commands from being recorded in the command history. This feature is useful when you want toย hide sensitive data, reduce clutter, or ignore repetitive commands.

To exclude commands automatically and make the settings permanent, add the following lines to the ~/.bashrc file :

export HISTCONTROL=ignoreboth
export HISTIGNORE="passwd:secret_command*"
Exclude commands from  history in Nano terminal output

The lines are:

  • HISTCONTROL. Skips duplicate commands and any that start with a space, with the ignoreboth option.
  • HISTIGNORE. Defines a list of patterns that Bash ignores when recording history. Separate patterns with colons. In this example, any command that matches passwd or begins with secret_command is omitted from history.

Commands excluded with these settings do not appear in the output of the history command or the .bash_history file. After you add the lines, make the changes permanent with:

source ~/.bashrc

To temporarily hide a command without any modification to the configuration files, type it with a Space character. For example:

 sudo apt install vim
space  sudo apt install vim terminal output

Export or Backup Bash History

Back up Bash history to preserve command logs for audits, documentation, or configuration transfers to another system.

The history command output can be redirected to a file to create a backup of all recorded commands.

To export the full history from the current session, run:

history > ~/history_backup.txt

This command has no output, but saves the history list to the history_backup.txt file in the user's home directory. The redirection overwrites the file if it already exists.

To append instead of overwrite, use:

history >> ~/history_backup.txt

The file contains commands identical to the history output.

When you redirect the history output to a file, it creates a plain text copy that remains readable and easy to edit, but it grows large over time. However, compress the backup to reduce its size. This makes it more suitable for long-term storage or archiving on backup drives and remote systems.

To compress the backup, use gzip:

gzip ~/history_backup.txt

If the process is successful, the command prints no output.

Another option is to move or copy the file to external storage or a version control repository to maintain a command record across systems.

To restore the history on another system or after a reset, merge it with the existing ~/.bash_history file with cat:

cat ~/history_backup.txt >> ~/.bash_history

This approach ensures previously saved commands become available in future sessions without overwriting existing history data.

Bash History Shortcuts

Bash provides several keyboard shortcuts that make it easier to recall, search for, and reuse previous commands without retyping them. These shortcuts speed up terminal work and allow interactive command navigation and editing.

The following table presents Bash history keyboard shortcuts:

ShortcutDescription
Up / Down ArrowScrolls through previous commands in the current session. Shows commands in chronological order, most recent at the bottom.
Ctrl+RStarts reverse incremental search through history. Finds commands containing typed text.
Ctrl+SSearches forward through history (if enabled; often disabled by default)
Ctrl+P / Ctrl+NNavigates backward (Ctrl+P) or forward (Ctrl+N) through the command list.

An alternative is to use the fc command. It lets users edit and rerun previous commands directly from a text editor. For example, to open and modify the last executed command, run:

fc
fc terminal output

Bash opens the last executed command, in this case sudo apt update, in the default editor.

After you save and close the file, the edited command executes automatically. This method is used to fix syntax errors or rerun complex commands with small changes.

Bash History Designators

Bash history designators allow you to reference and reuse previous commands without retyping them. Designators are a subset of history expansion operators that all begin with an exclamation mark (!) and specify which previous command to use.

These operators are not used with the history command itself. However, they allow quick execution of past commands without retyping them.

Key designators include:

  • !!. Repeats the last executed command.
  • !n. Executes the command at position n in the history list.
  • !string. Runs the most recent command that begins with string.
  • !?string?. Runs the most recent command that contains string anywhere.

The practical uses of designators are elaborated in earlier sections of the text.

Note: Verify the command before using a history designator. Expansion operators execute the referenced command immediately, which have unintended or dangerous effects if misused.

Bash History Modifiers

Bash history modifiers let you preview or modify previously executed commands before running them.

For instance, some key modifiers allow you to replace the first occurrence of a string in the previous command:

^old^new

In this example, the last command was echo foobar. To change foo to bar, run:

^foo^bar
^foo^bar terminal output

This effectively executes echo barbar, and the output is barbar.

Another modifier prints a recalled command without executing it, which lets you verify it first. Use:

!!:p
!!:p terminal output

The command prints the most recent command instead of running it.

Bash also lets you extract arguments from previous commands with specific shortcuts called word designators. These modifiers expand to specific arguments from earlier commands and let you reuse them without retyping. In practice, they are useful when you want to repeat similar commands, edit files, or rerun long operations with slight changes.

The most common ones are:

  • !$. Expands to the last argument of the previous command.
  • !*. Expands to all arguments of the previous command.
  • !^. Expands to the first argument of the previous command.

The following examples use echo to demonstrate the expansions without executing the original command. In practice, these shortcuts work well combined with any command.

For instance, to get the last argument, run:

echo !$
echo !$ terminal output

Since in this case, the previous command was sudo apt install vim, the designator prints vim in the terminal.

To extract all arguments from the previous command, execute:

echo !*
echo !* terminal output

If you use the same example command, the output prints apt install vim.

To print the first argument of the previous command, type:

echo !^
echo !^ terminal output

This outputs apt for the previous example.

If you need to extract arguments from an older command in your history rather than the most recent one, reference it by its command number. For instance, if command 42 in your history was tar -cvf project_release.tar.gz src/, retrieve the second argument with:

echo !42:2
echo !42:2 terminal output

This outputs project_release.tar.gz, which lets you reuse a specific parameter without retyping the entire command.

Note: Always verify commands before execution. Modifiers can unintentionally run commands if used without caution.

Conclusion

This tutorial explained what Bash history is and where it is stored. It also elaborated on the history command syntax and options. The text also provided examples on how to work with Bash history, its shortcuts, designators, and modifiers.

Next, learn how to create and use a Bash alias.

Was this article helpful?
YesNo