Event History

This week, we use the BASH history utility to retrieve previously

executed shell commands.

BASH automatically stores a limited number of previously typed

commands, the default limit being 500 commands. Assigning a different

value to the variable HISTSIZE changes the default limit. Each command,

technically referred to as an "event", associates with a number

according to their sequence (i.e., the most recent event has the

highest number). The "history" command lists events and their

associated numbers:

$ history

1 ls

2 mv payroll febpayroll

3 vi myprog.c

In this example, the user executed three commands before

typing "history". BASH enables you to traverse previously typed

commands by pressing the UP-ARROW key (to move up to the previous event

in the history list) and DOWN-ARROW (to move down to the next event in

the history list). In most cases, sequential access is sufficient;

however, repeatedly pressing UP-ARROW can be tedious when scrolling

through a lengthy list of commands. Instead, you can use the ! operator

followed by the command's associated number to retrieve a specific


$ history

1 ls

2 mv payroll febpayroll

3 vi myprog.c

$ !1


In the above example, typing "!1" retrieves event number 1. You can

also use an initial substring that appears in the command you wish to

retrieve. For example:

$ !mv

mv payroll febpayroll

In this case, following ! with the substring "mv" retrieves the

command "mv payroll febpayroll", which begins with "mv".

You may also use a negative number after the ! operator to reference an

event using an offset from the list's end. In other words, you can

instruct the history utility to access n commands from the most recent

one. For example:

$ !-2

mv payroll febpayroll

Let's examine how the "!-2" is processed. The following table contains

the list of events and their negative offsets:

event # offset

1 typing !-3 puts us here

2 typing !-2 puts us here

3 typing !-1 puts us here

As you can see, typing "!-2" retrieves event number 2, which is "mv

payroll febpayroll".

If you type only ! without a number or an initial substring, the last

command is assumed:


vi myprog.c

ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon