So here is a treat from linux side 🙂 and it’s about using the bash shell more efficiently by using the many facilities that the history command provides.
So, let’s start with the basics:
The above command simply prints the last N commands you executed, where N = the value of shell variable $HISTSIZE
So, now u know how to change the length of history just append
export $HISTSIZE=<your value>
in your .bashrc file. Strive for infinite history or zero history for the naughty ones 😛 . Don’t worry i’ll also tell how to disable history in a later post 😛 .
$ history 10
The above command simply prints the last 10 commands you executed. You can change 10 to any number. And for those you testers out there do test what if value you type is greater than $HISTSIZE.
But now, things get interesting with the introduction of ! operator.
! denotes start of a command to be completed by bash.
Prints and executes the last command.
where N is any number; prints and executes the command preceeded by number N in the output of your history command.
where N is any number; prints and executes the Nth last command you executed.
And now the next one is very interesting, it’s
$ date; !#
What !# does is just repeats what is on the left of it. So the above command expands to:
$ date; date;
So date is printed twice.
But be careful, this has exponential effect 😐 , i.e
$ date; !# !#
prints date 4 times and not three times. Since date; !# expands to date; date; !# and then !# repeats it.
So now you know that printing date 1024 times is not a looping problem but a “bang hash” cakewalk 😛 . Why not try it yourself.
The next one is very useful for all the programmers out there and it is !$. !$ simply substitutes the second argument to the previous command, see below:
$ make programname $ ./!$
The above compiles the program named programname.c and then runs it. Handy isn’t it 🙂 . You can always think of more uses for !$.
Next one is even more interesting. We are going to search history now 😐 . Just press Ctrl + R at your prompt. You will get a new prompt like this:
Now at this prompt type any word and you will be shown the most recent command having that word as substring.
(reverse-i-search)`gcc': gcc semaphore.c -o semaphore -lpthread
Press Enter to execute the command or Ctrl+R to go to older commands containing that as substring. You can also press Ctrl+O when a command is shown to execute the current one and move to the next one.
So, that’s all for this time. I’ll do at least one more post on history in the future to talk about more advanced operators and customizing shopt command.
Please comment if you like it or have any suggestions or doubts.