history - Linux


Overview

The history command in Linux is a shell utility used to display the command line history of the current user. It lists previously executed shell commands, allowing users to review or repeat commands very efficiently. This command is highly useful in daily operations for recalling complex commands, learning, debugging, and tracking user activity on multi-user systems.

Syntax

The basic syntax for the history command is:

history [options] [history number]

Parameters:

  • [options]: Options to modify the behavior of the command.
  • [history number]: Specifies the number of the most recent commands to display. If omitted, history will list all commands available in the command history.

Options/Flags

  • -c: Clear the history list by deleting all of the entries.
  • -d offset: Delete the history entry at position offset.
  • -a: Append the new history lines (those not already written) to the history file.
  • -n: Read the history lines not already read from the history file into the current history list.
  • -r: Read the contents of the history file and use them as the current history.
  • -w: Write out the current history to the history file, overwriting the history file.
  • -p: Perform history expansion on the following args and display the result on the standard output.
  • -s: Store the args in the history list as a single entry.

Examples

  1. Viewing the entire command history:

    history
    
  2. Displaying the last 5 commands:

    history 5
    
  3. Clearing the command history:

    history -c
    
  4. Deleting a specific entry by its offset (e.g., offset 720):

    history -d 720
    
  5. Saving recent commands to the history file immediately:

    history -a
    

Common Issues

  1. Limit of command history: By default, shell might limit the number of commands saved in history. You can change this limit by setting the HISTSIZE and HISTFILESIZE variables in your shell’s configuration file (e.g., .bashrc).
  2. Commands not saved in history: Some commands, especially those starting with a space, may not be saved in history. This behavior can be changed using the shell settings.

Integration

The history command can be coupled with other commands for powerful command-line workflows:

  • Piping history to grep to find specific commands:
    history | grep "mkdir"
    
  • Executing a specific command from history:
    !<history_number>
    

    Replace <history_number> with the actual number from the history listing to re-execute the command.

  • grep: Useful for filtering output from history.
  • awk, sed: For more complex manipulation of history output.
  • !: Re-executes a command from history.

For additional details, refer to the Bash documentation available at: Bash Reference Manual