A little bit of history

By  

Just about anyone who works on the command line of a Unix/Linux systems knows about history. Having the ability to repeat their most recent command by just typing !! or the most recent command that starts with a particular letter by typing something like !s saves them a lot of typing and a lot of typos. But these uses of the history feature of the shell only scratch the surface of what it can do for you.

You can also edit prior commands, find prior commands based on particular substrings, determine how much history is preserved for you, remove commands from your history, filter (omit) commands so they're never save in your history, and clear your history altogether.

How does the history command work? It stores the commands that you type in a history buffer that isn't written to your history file -- which might be .history or .bash_history -- until you log out. When you type history on the command line, what you see will be a combination of the commands you've typed since you started your current shell and earlier commands that were recorded in your history file.

If you start a second shell by typing /bin/bash, enter some commands, exit that shell, and type some additional commands, the commands that you entered in the subshell will appear in your history file prior to those you entered before starting the shell because that shell exited first. Try this:

$ echo 1
1
$ echo 2
2
$ echo 3
3
$ /bin/bash
$ echo 4
4
echo 5
5
$ exit
$ history 5
   42  echo 1
   43  echo 2
   44  echo 3
   45  /bin/bash
   46  history 5

Log off and back in and then:

$ tail .bash_history
history
/bin/bash
echo 4
echo 5
echo 1
echo 2
echo 3
/bin/bash
history 5
tail -5 .bash_history

Notice how the echoes of 1, 2 and 3 appear after 4 and 5 even though you entered those commands earlier.

Any time you start a new shell, you will see only the commands you have typed since invoking it and commands that were previously stored in your history file. Run this script and it will not see any of the commands you typed just before running it.

#!/bin/bash

whoami
history 10

Run this one and it will -- because this one doesn't spawn a new shell.

whoami
history 10

You can see a portion of your history by using an argument with the history command. For example, history 5 shows you only the most recent 5 commands.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Operating SystemsWhite Papers & Webcasts

See more White Papers | Webcasts

Answers - Powered by ITworld

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question