Linux

history

Command-line history usage guide.

#linux #shell #history

Basic Usage

Display the command history list with line numbers.

history

Display the last n lines of the history list.

history 10

Clear the history list.

history -c

Delete the history entry at position n.

history -d 100

History Expansion

Reuse parts of previous commands to speed up your workflow.

CommandDescription
!!Run the last command again.
!$Last argument of the last command.
!^First argument of the last command.
!*All arguments of the last command.
!:nThe nth argument of the last command.
!nRun command number n from history.
!-nRun the command n lines back.
!stringRun the most recent command starting with string.
!?string?Run the most recent command containing string.
^old^newReplace old with new in the previous command and run it.

Searching History

Interactively search through command history (reverse search).

Ctrl + R

Search forward in history (if configured).

Ctrl + S


Configuration

Environment variables that control history behavior.

VariableDescription
HISTSIZEThe number of commands to remember in the command history.
HISTFILESIZEThe maximum number of lines contained in the history file.
HISTFILEThe name of the file in which command history is saved (default ~/.bash_history).
HISTCONTROLControls how commands are saved (e.g., ignorespace, ignoredups, ignoreboth).
HISTTIMEFORMATIf set, the time stamp is printed associated with each history entry.

Example configuration in .bashrc:

Ignore duplicate commands and commands starting with a space.

export HISTCONTROL=ignoreboth

Append to the history file instead of overwriting it.

shopt -s histappend

Set in-memory history length.

export HISTSIZE=1000

Set on-disk history length.

export HISTFILESIZE=2000

Add timestamps to history entries.

export HISTTIMEFORMAT="%F %T "

Persistent History

Write current history to the history file.

history -w

Append current history to the history file.

history -a

Read the history file and append to the current history list.

history -r