Home > Articles > Operating Systems, Server > Linux/UNIX/Open Source

  • Print
  • + Share This
This chapter is from the book

History

The history mechanism, a feature adapted from the C Shell, maintains a list of recently issued command lines, also called events, providing a quick way to reexecute any of the events in the list. This mechanism also enables you to execute variations of previous commands and to reuse arguments from them. You can replicate complicated commands and arguments that you used earlier in this login session or in a previous one and enter a series of commands that differ from one another in minor ways. The history list also serves as a record of what you have done. It can prove helpful when you have made a mistake and are not sure what you did or when you want to keep a record of a procedure that involved a series of commands.

The history builtin (both in bash and tcsh) displays the history list. If it does not, read on—you need to set some variables.

Variables That Control History

The TC Shell's history mechanism is similar to bash's but uses different variables and has other differences. See page 342 for more information.

The value of the HISTSIZE variable determines the number of events preserved in the history list during a session. A value in the range of 100 to 1,000 is normal.

When you exit from the shell, the most recently executed commands are saved in the file given by the HISTFILE variable (the default is ~/.bash_history). The next time you start the shell, this file initializes the history list. The value of the HISTFILESIZE variable determines the number of lines of history saved in HISTFILE (not necessarily the same as HISTSIZE). HISTSIZE holds the number of events remembered during a session, HISTFILESIZE holds the number remembered between sessions, and the file designated by HISTFILE holds the history list. See Table 8-7.

Table 8-7. History variables

Function

Variable

Default

Maximum number of events saved during a session

HISTSIZE

500 events

Location of the history file

HISTFILE

~/.bash_history

Maximum number of events saved between sessions

HISTFILESIZE

500 events

Event number

The Bourne Again Shell assigns a sequential event number to each command line. You can display this event number as part of the bash prompt by including \! in PS1 (page 286). Examples in this section show numbered prompts when they help to illustrate the behavior of a command.

Give the following command manually or place it in ~/.bash_profile (to affect future sessions) to establish a history list of the 100 most recent events:

$ HISTSIZE=100

The following command causes bash to save the 100 most recent events across login sessions:

$ HISTFILESIZE=100

After you set HISTFILESIZE, you can log out and log in again, and the 100 most recent events from the previous login session will appear in your history list.

Give the command history to display the events in the history list. The list of events is ordered with oldest events at the top of the list. A tcsh history list includes the time the command was executed. The following history list includes a command to modify the bash prompt so that it displays the history event number. The last event in the history list is the history command that displayed the list.

32 $ history | tail
23 PS1="\! bash$ "
24 ls -l
25 cat temp
26 rm temp
27 vim memo
28 lpr memo
29 vim memo
30 lpr memo
31 rm memo
32 history | tail

As you run commands and your history list becomes longer, it may run off the top of the screen when you use the history builtin. Pipe the output of history through less to browse through it, or give the command history 10 to look at the ten most recent commands.

Reexecuting and Editing Commands

You can reexecute any event in the history list. This feature can save you time, effort, and aggravation. Not having to reenter long command lines allows you to reexecute events more easily, quickly, and accurately than you could if you had to retype the entire command line. You can recall, modify, and reexecute previously executed events in three ways: You can use the fc builtin (covered next); the exclamation point commands page 299; or the Readline Library, which uses a one-line vi- or emacs-like editor to edit and execute events (page 304).

fc: Displays, Edits, and Reexecutes Commands

The fc (fix command) builtin (not in tcsh) enables you to display the history list and to edit and reexecute previous commands. It provides many of the same capabilities as the command line editors.

Viewing the History List

When you call fc with the –1 option, it displays commands from the history list. Without any arguments, fc–1 lists the 16 most recent commands in a numbered list, with the oldest appearing first:

$ fc -l
1024    cd
1025    view calendar
1026    vim letter.adams01
1027    vim letter.adams01
1028    lpr letter.adams01
1029    cd ../memos
1030    ls
1031    rm *0405
1032    fc -l
1033    cd
1034    pwd
1035    ls
...

The fc builtin can take zero, one, or two arguments with the –1 option. The arguments specify the part of the history list to be displayed:

   fc –l [ first [last]]

The fc builtin lists commands beginning with the most recent event that matches first . The argument can be an event number, the first few characters of the command line, or a negative number, which is taken to be the n th previous command. If you provide last , fc displays commands from the most recent event that matches first through the most recent event that matches last . The next command displays the history list from event 1027 through event 1030:

$ fc -l 1027 1030
1027     vim letter.adams01
1028     lpr letter.adams01
1029     cd ../memos
1030     ls

The following command lists the most recent event that begins with view through the most recent command line that begins with whereis:

$ fc -l view pwd
1025     view calendar
1026     vim letter.adams01
1027     vim letter.adams01
1028     lpr letter.adams01
1029     cd ../memos
1030     ls
1031     rm *0405
1032     fc -l
1033     cd
1034     pwd

To list a single command from the history list, use the same identifier for the first and second arguments. The following command lists event 1027:

$ fc -l 1027 1027
1027   vim letter.adams01

Editing and Reexecuting Previous Commands

You can use fc to edit and reexecute previous commands.

   fc [–e editor] [first [last]]

When you call fc with the –e option followed by the name of an editor, fc calls the editor with event(s) in the Work buffer. Without first and last , fc defaults to the most recent command. The next example invokes the vi(m) editor to edit the most recent command:

$ fc -e vi

The fc builtin uses the stand-alone vi(m) editor. If you set the FCEDIT variable, you do not need to use the –e option to specify an editor on the command line. Because the value of FCEDIT has been changed to /usr/bin/emacs and fc has no arguments, the following command edits the most recent command with the emacs editor:

$ export FCEDIT=/usr/bin/emacs
$ fc

If you call it with a single argument, fc invokes the editor on the specified command. The following example starts the editor with event 21 in the Work buffer. When you exit from the editor, the shell executes the command:

$ fc 21

Again you can identify commands with numbers or by specifying the first few characters of the command name. The following example calls the editor to work on events from the most recent event that begins with the letters vim through event 206:

$ fc vim 206

Reexecuting Commands Without Calling the Editor

You can reexecute previous commands without going into an editor. If you call fc with the –s option, it skips the editing phase and reexecutes the command. The following example reexecutes event 1028:

$ fc -s 1028
lpr letter.adams01

The next example reexecutes the previous command:

$ fc -s

When you reexecute a command you can tell fc to substitute one string for another. The next example substitutes the string john for the string adams in event 1028 and executes the modified event:

$ fc -s adams=john 1028
lpr letter.john01

Using an Exclamation Point (!) to Reference Events

The C Shell history mechanism uses an exclamation point to reference events and is available under bash and tcsh. It is frequently more cumbersome to use than fc but nevertheless has some useful features. For example, the !! command reexecutes the previous event, and the !$ token represents the last word on the previous command line.

You can reference an event by using its absolute event number, its relative event number, or the text it contains. All references to events, called event designators, begin with an exclamation point (!). One or more characters follow the exclamation point to specify an event.

You can put history events anywhere on a command line. To escape an exclamation point so that it is treated literally instead of as the start of a history event, precede it with a backslash (\) or enclose it within single quotation marks.

Event Designators

An event designator specifies a command in the history list. See Table 8-8 on page 301 for a list of event designators.

Table 8-8. Event designators

Designator

Meaning

!

Starts a history event unless followed immediately by SPACE, NEWLINE, =, or (.

!!

The previous command.

! n

Command number n in the history list.

! n

The n th preceding command.

! string

The most recent command line that started with string .

!? string [?]

The most recent command that contained string . The last ? is optional.

!#

The current command (as you have it typed so far).

!{ event }

The event is an event designator. The braces isolate event from the surrounding text. For example, !{–3}3 is the third most recently executed command followed by a 3.

!! reexecutes the previous event

You can always reexecute the previous event by giving a !! command. In the following example, event 45 reexecutes event 44:

44 $ ls -l text
-rw-rw-r--   1 alex alex 45 Apr 30 14:53 text
45 $ !!
ls -l text
-rw-rw-r--   1 alex alex 45 Apr 30 14:53 text

The !! command works whether or not your prompt displays an event number. As this example shows, when you use the history mechanism to reexecute an event, the shell displays the command it is reexecuting.

!n event number

A number following an exclamation point refers to an event. If that event is in the history list, the shell executes it. Otherwise, the shell displays an error message. A negative number following an exclamation point references an event relative to the current event.For example, the command !–3 refers to the third preceding event. After you issue a command, the relative event number of a given event changes (event –3 becomes event –4). Both of the following commands reexecute event 44:

51 $ !44
ls -l text
-rw-rw-r--  1 alex alex 45 Nov 30 14:53 text
52 $ !-8
ls -l text
-rw-rw-r--  1 alex alex 45 Nov 30 14:53 text

! string event text

When a string of text follows an exclamation point, the shell searches for and executes the most recent event that began with that string. If you enclose the string between question marks, the shell executes the most recent event that contained that string. The final question mark is optional if a RETURN would immediately follow it.

68 $ history 10
   59 ls -l text*
   60 tail text5
   61 cat text1 text5 > letter
   62 vim letter
   63 cat letter
   64 cat memo
   65 lpr memo
   66 pine jenny
   67 ls -l
   68 history
69 $ !l
ls -l
...
70 $ !lpr
lpr memo
71 $ !?letter?
cat letter
...

The Readline Library

Command line editing under the Bourne Again Shell is implemented through the Readline Library, which is available to any application written in C. Any application that uses the Readline Library supports line editing that is consistent with that provided by bash. Programs that use the Readline Library, including bash, read ~/.inputrc (page 308) for key binding information and configuration settings. The —noediting command line option turns off command line editing in bash.

vi mode

You can choose one of two editing modes when using the Readline Library in bash: emacs or vi(m). Both modes provide many of the commands available in the stand-alone versions of the vi(m) and emacs editors. You can also use the ARROW keys to move around. Up and down movements move you backward and forward through the history list. In addition, Readline provides several types of interactive word completion (page 306). The default mode is emacs; you can switch to vi mode with the following command:

$ set-o vi

emacs mode

The next command switches back to emacs mode:

$ set -o emacs

vi Editing Mode

Before you start make sure you are in vi mode.

When you enter bash commands while in vi editing mode, you are in Input mode (page 149). As you enter a command, if you discover an error before you press RETURN, you can press ESCAPE to switch to vi Command mode. This setup is different from the stand-alone vi(m) editor's initial mode. While in Command mode you can use many vi(m) commands to edit the command line. It is as though you were using vi(m) to edit a copy of the history file with a screen that has room for only one command. When you use the k command or the UP ARROW to move up a line, you access the previous command. If you then use the j command or the DOWN ARROW to move down a line, you will return to the original command. To use the k and j keys to move between commands you must be in Command mode; you can use the ARROW keys in both Command and Input modes.

In addition to cursor-positioning commands, you can use the search-backward (?) command followed by a search string to look back through your history list for the most recent command containing that string. If you have moved back in your history list, use a forward slash (/) to search forward toward your most recent command. Unlike the search strings in the stand-alone vi(m) editor, these search strings cannot contain regular expressions. You can, however, start the search string with a caret (^) to force the shell to locate commands that start with the search string. As in vi(m), pressing n after a successful search looks for the next occurrence of the same string.

You can also access events in the history list by using event numbers. While you are in Command mode (press ESCAPE), enter the event number followed by a G to go to the command with that event number.

When you use /, ?, or G to move to a command line, you are in Command mode, not Input mode. Now you can edit the command as you like or press RETURN to execute it.

Once the command you want to edit is displayed, you can modify the command line using vi(m) Command mode editing commands such as x (delete character), r (replace character), ~ (change case), and . (repeat last change). To change to Input mode, use an Insert (i, I), Append (a, A), Replace (R), or Change (c, C) command. You do not have to return to Command mode to run a command; simply press RETURN, even if the cursor is in the middle of the command line.

Refer to page 191 for a summary of vim commands.

emacs Editing Mode

Unlike the vi(m) editor, emacs is modeless. You need not switch between Command mode and Input mode because most emacs commands are control characters (page 208), allowing emacs to distinguish between input and commands. Like vi(m), the emacs command line editor provides commands for moving the cursor on the command line and through the command history list and for modifying part or all of a command. The emacs command line editor commands differ in a few cases from the commands in the stand-alone emacs editor.

In emacs you perform cursor movement by using both CONTROL and ESCAPE commands. To move the cursor one character backward on the command line, press CONTROL-B. Press CONTROL-F to move one character forward. As in vi, you may precede these movements with counts. To use a count you must first press ESCAPE; otherwise, the numbers you type will appear on the command line.

Like vi(m), emacs provides word and line movement commands. To move backward or forward one word on the command line, press ESCAPE b or ESCAPE f. To move several words by using a count, press ESCAPE followed by the number and the appropriate escape sequence. To get to the beginning of the line, press CONTROL-A; to the end of the line, press CONTROL-E; and to the next instance of the character c , press CONTROL-X CONTROL-F followed by c .

You can add text to the command line by moving the cursor to the correct place and typing the desired text. To delete text, move the cursor just to the right of the characters that you want to delete and press the erase key (page 25) once for each character you want to delete.

If you want to delete the entire command line, type the line kill character (page 25). You can type this character while the cursor is anywhere in the command line. If you want to delete from the cursor to the end of the line, use CONTROL-K.

Refer to page 243 for a summary of emacs commands.

Readline Completion Commands

You can use the TAB key to complete words you are entering on the command line. This facility, called completion, works in both vi and emacs editing modes and is similar to the completion facility available in tcsh. Several types of completion are possible, and which one you use depends on which part of a command line you are typing when you press TAB.

Command Completion

If you are typing the name of a command (the first word on the command line), pressing TAB results in command completion. That is, bash looks for a command whose name starts with the part of the word you have typed. If no command starts with what you have entered, bash beeps. If there is one such command, bash completes the command name for you. If there is more than one choice, bash does nothing in vi mode and beeps in emacs mode. Pressing TAB a second time causes bash to display a list of commands whose names start with the prefix you typed and allows you to finish typing the command name.

In the following example, the user types bz and presses TAB. The shell beeps (the user is in emacs mode) to indicate that several commands start with the letters bz. The user enters another TAB to cause the shell to display a list of commands that start with bz followed by the command line as the user had entered it so far:

$ bz U2192.GIF TAB (beep) U2192.GIF TAB
bzcat    bzdiff    bzip2     bzless
bzcmp     bzgrep    bzip2recover bzmore
$ bz U25A1.GIF

Next the user types c and presses TAB twice. The shell displays the two commands that start with bzc. The user types a followed by TAB and the shell then completes the command because only one command starts with bzca.

$ bz c U2192.GIF TAB 
   (beep) U2192.GIF TAB
bzcat bzcmp
$ bzca U2192.GIF TAB U2192.GIF t U25A1.GIF

Pathname Completion

Pathname completion, which also uses TABs, allows you to type a portion of a pathname and have bash supply the rest. If the portion of the pathname that you have typed is sufficient to determine a unique pathname, bash displays that pathname. If more than one pathname would match it, bash completes the pathname up to the point where there are choices so that you can type more.

When you are entering a pathname, including a simple filename, and press TAB, the shell beeps (if the shell is in emacs mode—in vi mode there is no beep). It then extends the command line as far as it can.

$ cat films/dar_ U2192.GIF TAB 
      (beep) cat films/dark_U25A1.GIF

In the films directory every file that starts with dar has k_ as the next characters, so bash cannot extend the line further without making a choice among files. You are left with the cursor just past the _ character. At this point you can continue typing the pathname or press TAB twice. In the latter case bash beeps, displays your choices, redisplays the command line, and again leaves the cursor just after the _ character.

$ cat films/dark_ U2192.GIF TAB 
   (beep) U2192.GIF TAB
dark_passage dark_victory
$ cat films/dark_ U25A1.GIF

When you add enough information to distinguish between the two possible files and press TAB, bash displays the unique pathname. If you enter p followed by TAB after the _ character, the shell completes the command line:

$ cat films/dark_ p U2192.GIF TAB U2192.GIF assage

Because there is no further ambiguity, the shell appends a SPACE so you can finish typing the command line or just press RETURN to execute the command. If the complete pathname is that of a directory, bash appends a slash (/) in place of a SPACE.

Variable Completion

When typing a variable name, pressing TAB results in variable completion, where bash tries to complete the name of the variable. In case of an ambiguity, pressing TAB twice displays a list of choices:

$ echo $HO U2192.GIF TAB U2192.GIF TAB
$HOME   $HOSTNAME $HOSTTYPE
$ echo $HO M U2192.GIF TAB U2192.GIF E

.inputrc: Configuring Readline

The Bourne Again Shell and other programs that use the Readline Library read the file specified by the INPUTRC environment variable to obtain initialization information. If INPUTRC is not set, these programs read the ~/.inputrc file. They ignore lines of .inputrc that are blank or that start with a pound sign (#).

Variables

You can set variables in .inputrc to control the behavior of the Readline Library using the following syntax:

   set variable value

Table 8-11 lists some variables and values you can use. See Readline Variables in the bash man or info page for a complete list.

Table 8-11. Readline variables

Variable

Effect

editing-mode

Set to vi to start Readline in vi mode. Set to emacs to start Readline in emacs mode (the default). Similar to the set –o vi and set –o emacs shell commands (page 304).

horizontal-scroll-mode

Set to on to cause long lines to extend off the right edge of the display area. Moving the cursor to the right when it is at the right edge of the display area shifts the line to the left so you can see more of the line. You can shift the line back by moving the cursor back past the left edge. The default value is off, which causes long lines to wrap onto multiple lines of the display.

mark-directories

Set to off to cause Readline not to place a slash (/) at the end of directory names it completes. Normally it is on.

mark-modified-lines

Set to on to cause Readline to precede modified history lines with an asterisk. The default value is off.

Key Bindings

You can specify bindings that map keystroke sequences to Readline commands, allowing you to change or extend the default bindings. As in emacs, the Readline Library includes many commands that are not bound to a keystroke sequence. To use an unbound command, you must map it using one of the following forms:

   
      keyname: command_name
   

   
      "keystroke_sequence" : command_name
   

In the first form, you spell out the name for a single key. For example, CONTROL-U would be written as control-u. This form is useful for binding commands to single keys.

In the second form, you specify a string that describes a sequence of keys that will be bound to the command. You can use the emacs-style backslash escape sequences to represent the special keys CONTROL (\C), META (\M), and ESCAPE (\e). Specify a backslash by escaping it with another backslash: \\. Similarly, a double or single quotation mark can be escaped with a backslash: \ "or \'.

The kill-whole-line command, available in emacs mode only, deletes the current line. Put the following command in .inputrc to bind the kill-whole-line command (which is unbound by default) to the keystroke sequence CONTROL-R.

control-r: kill-whole-line

bind

Give the command bind –P to display a list of all Readline commands. If a command is bound to a key sequence, that sequence is shown. Commands you can use in vi mode start with vi. For example, vi-next-word and vi-prev-word move the cursor to the beginning of the next and previous words, respectively. Commands that do not begin with vi are generally available in emacs mode.

Use bind –q to determine which key sequence is bound to a command:

$ bind -q kill-whole-line
kill-whole-line can be invoked via "\C-r".

You can also bind text by enclosing it within double quotation marks (emacs mode only):

"QQ": "The Mac OS X Operating System"

This command causes bash to insert the string The Mac OS X Operating System when you type QQ.

Conditional Constructs

You can conditionally select parts of the .inputrc file using the $if directive. The syntax of the conditional construct is

   $if 
   
      test[= value]
   
           
   
      commands
   
    
   [$else
           
   
      commands]
   

   $endif

where test is mode, term, or bash. If test equals value or if test is true, this structure executes the first set of commands . If test does not equal value or if test is false, it executes the second set of commands if they are present or exits from the structure if they are not present.

The power of the $if directive lies in the three types of tests it can perform.

  1. You can test to see which mode is currently set.

    $ if mode=vi
    
          

    The preceding test is true if the current Readline mode is vi and false otherwise. You can test for vi or emacs.

  2. You can test the type of terminal.

    $ if term=xterm
    
          

    The preceding test is true if the TERM variable is set to xterm. You can test for any value of TERM.

  3. You can test the application name.

    $ if bash
    
          

    The preceding test is true when you are running bash and not another program that uses the Readline Library. You can test for any application name.

These tests can customize the Readline Library based on the current mode, the type of terminal, and the application you are using. They give you a great deal of power and flexibility when using the Readline Library with bash and other programs.

The following commands in .inputrc cause CONTROL-Y to move the cursor to the beginning of the next word regardless of whether bash is in vi or emacs mode:

$ cat ~/.inputrc
set editing-mode vi
$if mode=vi
       "\C-y": vi-next-word
    $else
       "\C-y": forward-word
$endif

Because bash reads the preceding conditional construct when it is started, you must set the editing mode in .inputrc. Changing modes interactively using set will not change the binding of CONTROL-Y.

For more information on the Readline Library, open the bash man page and give the command /^READLINE, which searches for the word READLINE at the beginning of a line.

  • + Share This
  • 🔖 Save To Your Account