One of the extensively used command in UNIX world is the history command. Every flavor of UNIX has the history command. The bash shell stores a history of commands entered, which can be used to repeat commands by using the history command. By default, it’ll show the previous 1000 commands that were used.
Here’s a sample output of the command history:
# history 1 uname -a 2 clear 3 ssh root@192.168.1.50 4 exit 5 ls 6 clear 7 echo "Hello" ........
The bash history mechanism supports a variety of advanced ways of retrieving commands from the history list. Below are some of the ways to use the bash history command :
1. Listing last n commands used
By default, history command shows the last 1000 commands used. If you want to list only last few commands fired by the user use “history n”. For example, to display last 5 commands fired :
# history 5 504 uname -a 505 who am i 506 date 507 echo "Hi" 508 history 5
2. Repeating last command
To repeat the last command executed :
# echo "I am history" I am history # !! echo "I am history" I am history
3. Repeat last command starting with some character
!char = repeats last command that started with char. For example :
# !uname uname -a Linux geeklab 2.6.32-504.el6.x86_64 #1 SMP Tue Sep 16 01:56:35 EDT 2014 x86_64 x86_64 x86_64 GNU/Linux
4. Repeat last command by its number
!num = repeats a command by its number in history output. For example :
# !1010 ls -lrth total 197M -rw-r--r-- 1 root root 512K May 25 2015 file1 drwxr-xr-x 2 root root 4.0K Jun 1 2016 dir1
5. Repeat last command that contains some character
!?command = repeats last command that contains (as opposed to started with [!char]) command. Example :
# echo "I am legend" I am legend # !?legend echo "I am legend" I am legend
6. Repeat the nth last command
!-n = repeats a command entered n commands back
# !-3 uname -a Linux VMAX3Linux 2.6.32-358.el6.x86_64 #1 SMP Tue Jan 29 11:47:41 EST 2013 x86_64 x86_64 x86_64 GNU/Linux
7. Searching for a command in history and executing it
Ctrl-r = search for a command in command history and execute it once you find a match.
# (reverse-i-search)`uname': uname -a
CentOS / RHEL : How to get the date and time of executed command in the history command output
CentOS / RHEL : How to disable BASH shell history