3.11. Command History and Tab Completion

It does not take long before the thought of typing the same command over and over becomes unappealing. One minor typing error can ruin lines of a series of commands.

One solution is to use the command line history. By scrolling with the [Up] and [Down] arrow keys, you can find plenty of your previously typed commands.

Try it by taking a look again at sneakers.txt (created in Section 3.8.1 Using Redirection). The first time, however, at the shell prompt, type:

cat sneakrs.txt

Nothing happens, of course, because there is no sneakrs.txt file. Use the [Up Arrow] key to bring back the command, then use the [Left Arrow] key to get to the point where we missed the "e." Insert the letter and press [Enter] again.

We now see the contents of the sneakers.txt file.

By default, up to 500 commands can be stored in the bash command line history file.

TipTip
 

By typing the env command at a shell prompt, we can see the environment variable that controls the size of the command line history. The line which reads, HISTFILESIZE=500 shows the number of commands that bash stores.

The command line history is actually kept in a file, called .bash_history in your login directory. We can read it in a number of ways: by using vi, cat, less, more, and others.

Be aware that the file can be long. To read it with the more command, from your home directory type:

more .bash_history

To move forward a screen, press [Space]; to move back a screen, press [B]; to quit, press [Q].

TipTip
 

To find a command in your history file without having to keep hitting the arrow keys or page through the history file, use grep (refer to Section 3.10.3 The grep Command). Here is how you can quickly find a previously used command: say you are searching for a command that is similar to cat sneak-something. You have used the command before and you think it might be in your history file. At the shell prompt, type:

history | grep sneak

Another time-saving tool is known as command completion. If you type part of a file, command, or pathname and then press the [Tab] key, bash presents you with either the remaining portion of the file/path, or a beep (if sound is enabled on your system). If you hear a beep, press [Tab] again to obtain a list of the files/paths that match what has been typed so far.

For example, if you forget the command updatedb, but remember a portion of the command, you can su - to root and use the following instructions. At the shell prompt, type up and press the [Tab] key twice. A list of possible completions is displayed, including updatedb and uptime. By typing the partial command upd and pressing [Tab] again, your command is completed for you.

When you are done working as root, type exit at the prompt; you are returned to your user account.

mirror server hosted at Truenetwork, Russian Federation.