History completion

From Linux Bash Shell Scripting Tutorial Wiki
Jump to navigation Jump to search

If you want to repeat the command typed at the bash prompt, use the history command.

Using history' to repeat bash commands

The bash shell keeps a record of your most recent commands and allows you to reuse them using various methods. The bash shell allows you to use the cursor keys to scroll through the list of stored command lines. It even comes with various command history shortcuts for editing and manipulating your command history. You save typing command when you use the history command.

How to see command history

Simply type history at the command prompt:

history
Linux history command

History completion

A number list scrolls by very quickly showing many commands. You probably do not need to see all of the last 1000 commands.

How to display the last 15 commands

history {number}
history 15

Of course, you can filter results using the [grep command] or use pager such as [more command]/[less command] too:

history | less
history | more
## search for tar command ##
history | grep tar

history command shortcuts

Here are other command history shortcuts which may be useful with bash shell session.

How to executes the last command in the history

Type !! run the last command in the history:

date
!!

Say you want to run a command as root user, but you forgot:

ls /root
sudo !!

How to executes the command which is numbered 42 in the history file

The syntax is

!number
!42
!63
## see history ##
history
## recall a very long command with history number  402 ##
!402
sudo !!
## Repeat the command entered 5 events ago ##
!-5

How to run a command with the most recent matching string from the history

The syntax is

!string
!word
## executes a command with the most recent matching string named sudo ##
!sudo
!yum
!dnf
!date
## repeat the most recent command beginning with "rsync" ##
!rsync

Up and Down arrow keys

Press the up arrow (or [CTRL]+[P]) to move back through previous commands in your history list. Furthermore, press the down arrow (or [CTRL]+[N]) moves you forward through the commands until you find the command you need to run. Finally, hit [Enter] key to execute the command.

CTRL + r

Another option to recall or repeat previous commands from history is typing [CTRL]+[r] ( that's holding down the Ctrl key and typing a lower case r). This is called a reverse search. After you type [CTRL]+[r], start typing the beginning of a previously entered command.