How to run previously executed command in Linux terminal

One of most useful feature of Linux is command history, where all previously run command are stored in history file (/home/$USER/.bash_history). This guide, cover how to run previously executed command in Linux terminal.

How to run previously executed command in Linux terminal
Location of bash history file

Usually scrolling with up arrow keys one can retrieve a previously executed commands. But list of commands is long pressing arrow key continuously will take time to find one you have used.

Ways to run previously executed command in Linux terminal

Use history command to view previously run command in terminal

Running history command lets you view previously run commands in terminal. Below is output of history command in Fedora. The output shows a list of commands with a number before each command.

How to run previously executed command in Linux terminal
Use history command to view previously run command

Search for specific command using history command with Grep

grep command can be used to filter history for commands run with particular characters

Syntax

history | grep [command you want to search for]

Example

history | grep ls

Search for command starting from specific letter in history

To search for command starting from specific letter use ! with characters of command

Syntax

![characters of command]

Example

!l

!ls

Note: if you are filtering command using single character and only one command exists in history, in that case it will get directly executed. Running commands without through knowledge may harm your system, use command with care.

Run previously executed command from Linux terminal

The numbers  shown in above command can be used to run any command from list of output of history. Like if I want to run command number 6 I will simply type !6.

Syntax

![sequence number of command in history]

Example

!6

There is another method to run old command from history. Just type exclamation mark followed by few alphabets of command you want to run – !l. Only disadvantage of these two methods is command will directly run command without asking for any confirmation.

These commands have been used in Fedora and Redhat Linux  Different version may show different output.