Skip to content

history Command in Linux

Summary

The history command in Linux displays a list of previously executed commands, allowing users to review, reuse, and manage their command-line interactions.

Introduction

The history command is a powerful tool for Linux users to track and manage their command-line activity. It allows you to view a list of commands you've executed, recall them for reuse, and even clear your command history for privacy. By default, the shell stores a certain number of commands in a history file (usually .bash_history in your home directory). The history command provides a way to interact with this file.

Use case and Examples

Displaying Command History

history
This command displays a numbered list of previously executed commands from the history file.

Displaying Last N Commands

history 10
This will display the last 10 commands from the history list. Replace 10 with any number to view that many recent commands.

Executing a Command from History

!123
This executes the command numbered 123 in the history list. Replace 123 with the desired command number.

Executing the Previous Command

!!
This re-executes the most recently executed command.

Executing a Command Containing a Specific String

!?string?
This executes the most recent command in the history that contains the specified string. For example, !?apt update? will execute the last command containing "apt update".

Clearing Command History

history -c
This clears the current shell's history list. Note that the .bash_history file on disk will not be updated until the shell exits or history -w is used.

Appending the Current History to History File

history -a
This appends the current session's history to the .bash_history file. Useful for ensuring the file is up-to-date before logging out.

Commonly used flags

Flag Description Example
-c Clears the history list. history -c (clears the history)
-d offset Deletes the history entry at position OFFSET. history -d 5 (deletes the 5th entry)
-a Append the new history lines to the history file. history -a (appends to the file)
-n Read all history lines not already read from the history file. history -n (reads new lines from file)
-r Read the contents of the history file and use them as the current history list. history -r (reads the history file)
-w Write the current history to the history file. history -w (writes the history to file)
-p arg1 arg2 ... Perform history substitution on the ARGs and display the result, without storing them in the history list. history -p 'echo hello world' (shows what echo hello world would execute as.)
-s arg Add the ARGs to the end of the history list as a single entry. history -s 'ls -l' (adds ls -l as the last history entry)


Share on Share on

Comments