How to manage Bash command history

Bash command history makes recent interactive commands available for recall, but the same list can keep mistyped commands, temporary one-liners, or sensitive text after terminal work is finished. Managing it means checking the current shell's history list, deleting the exact entry that should not remain, and writing the edited list only when the saved history file should change.

Bash keeps an in-memory history list for each running shell and uses HISTFILE, usually ~/.bash_history, for history saved between sessions. The history builtin displays entries by number, removes one entry with history -d, clears the current list with history -c, and overwrites the history file with history -w.

History cleanup starts in the terminal where the command was typed. Other open Bash sessions may still hold their own lists and can write them later, so clean the affected terminals before they exit when an unwanted command must be removed from disk.

Steps to manage Bash command history:

  1. Confirm the active saved history file.
    $ echo "$HISTFILE"
    /home/user/.bash_history

    If HISTFILE is unset or empty, Bash does not save history on shell exit and history -w has no file to update.

  2. List recent Bash history and identify the entry number to remove.
    $ history 5
        1  cd ~/project
        2  echo temporary-demo-command
        3  git status
        4  vim ~/.bashrc

    The number at the left is the history offset used by history -d. Run history without a number when the entry is farther back in the list.

  3. Delete the unwanted active history entry by number.
    $ history -d 2

    Entry numbers shift after deletion. Run history again before deleting another entry.

  4. Confirm the entry no longer appears in the active history.
    $ history 5
        1  cd ~/project
        2  git status
        3  vim ~/.bashrc
  5. Write the edited active history list to the history file.
    $ history -w

    history -w overwrites the file named by HISTFILE with the current in-memory list for this shell.

  6. Confirm the saved history file no longer contains the removed command.
    $ cat "$HISTFILE"
    cd ~/project
    git status
    vim ~/.bashrc

    HISTFILE normally points to ~/.bash_history. If it is unset, Bash may not save history for the current session.

  7. Clear the active session history only when every current entry should be removed.
    $ history -c

    history -c clears the current shell's in-memory history. Run history -w afterward only when the saved history file should also be overwritten with the cleared list.

  8. Write the cleared list to the history file when the saved file should be emptied too.
    $ history -w
  9. Confirm the saved history file is empty.
    $ cat "$HISTFILE"

    No output means the history file currently has no saved commands.