Use Bash more efficiently: History โ€“ Part 1

2 minute read

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:

$ history

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.

Examples:

$ !!

Prints and executes the last command.

$ !N

where N is any number; prints and executes the command preceeded by number N in the output of your history command.

$ !-N

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:

(reverse-i-search)`':

Now at this prompt type any word and you will be shown the most recent command having that word as substring.

For example:

(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.

Categories:

Updated:

Leave a Comment