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|
|!n||Refers to the command line n|
|!string||Invokes the command starting with “string”|
|!?string||Refers to the most recent command containing “string”|
|^string1^string2||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' [root@nyx log]#