In case you are wondering how to review your latest commands entered in your favorite Unix shell, below you have more than one option to achieve this goal.
The first and most known way is using the history command:
By typing history in your Linux shell will show on your screen the latest commands you entered with the user you are currently logged in.
It is important to mention that the Unix/Linux way of storing your history is pretty simple: basically the OS just stores your commands in a text file. That file can differ from one distro to another, but you can view the exact location of that file by typing echo $HISTFILE. You can see a sample below:
Knowing the file (location) the ways you can manipulate the output are multiple. For example:
cat $HISTFILE | more #(you can use less too)
View the history in a text editor:
View only specific columns:
history | cut -d' ' -f 4-
View only the last 20 lines:
history | tail -n 20
Or view the:
- last 5 “yum-install” commands from your history file:
history | grep "yum-install" | tail -n 5
- First 5 commands that contain “yum”
history | grep yum | head
Viewing your bash history is pretty easy. Type history in your shell and you will be presented with the latest 500 or 1000 (depends on distro/bash settings, ) commands you entered.
But what if you want to run one or more commands from the history file, how can that be accomplished ?
Well, the not so effective way is to type history | grep mycommand, then copy and paste in the terminal.
However, if your command expands on multiple lines the above procedure is pretty painful.
Here’s a more efficient way:
Introducing History expansion and the event designators:
||Repeat last command
||Start a history substitution
||Refers to the command line n
||Invokes the command starting with “string”
||Refers to the most recent command containing “string”
||Repeats the last command and replaces string1 with string2
Here are a couple of practical examples:
Repeats last command, in this case is whoami.
From the history file it Invokes the latest command containing hostname.
[root@nyx log]# tail /var/log/messages | head -n 2 #showing first 2 lines from /var/log/messages
Aug 22 19:39:56 euve59329 Plesk/Courier authd: No such user 'firstname.lastname@example.org' in mail authorization database
Aug 22 20:05:26 euve59329 Plesk/Courier authd: No such user 'email@example.com' in mail authorization database
[root@nyx log]# ^messages^mysqld.log #from the last command replace messages with mysqld.log and execute the command
tail /var/log/mysqld.log | head -n 2
140822 4:03:28 [ERROR] Invalid (old?) table or database name 'comment _subscribers'
140822 4:03:28 [ERROR] Invalid (old?) table or database name 'mp3-players'