How to Use History Command in Linux

The “history” command reveals the list of the command that the current user has been invoked. The command accepts passing a pattern as an argument to sort specific commands from the history.

General syntax for history command:

history [OPTIONS...]
Show used commands
history [number]

This command displays a limited number of previously executed commands.

Example: To print the last five commands you have used, type history 5.

show used commands
Delete commands from history list
history -d [number]

Use the -d option to delete commands from the history list.

Example: Removing the fifth (5) command from the history list.

delete commands from history
Search used command within history
history | grep [text]

The history | grep command helps you find commands that match a text pattern.

Example: Searching for a command that uses the word “cat.”

search within history
Clearing the history list
history -c

The -c (clear) option is used to clear all commands from the history list.

Example: Here are 5 commands that were used before, use history -c to clear the list.

clear history
Execute the command with event number

This command allows you to execute commands with an event number from the history list. There is no need to write a complete command.

Example: Let’s use the tenth command (!10) from the history list.

execute commands eent numbers
Write changes to bash_history file
history -w [filename]

Use this option to write all changes made in the current session to the bash_history file.

Example: Writing five previously used commands to the history-list file.

write to bash_history