10.3. Command Line Shortcuts

10.3.1. History

The history mechanism is built into the TC shell. It keeps in memory a sequentially numbered list of the commands, called events, that you have typed at the command line. As well as the number of the history event, it also keeps track of the time the event was entered at the terminal. When the shell reads a command from the terminal, it breaks the command line into words (using white space to designate a word break), saves the line to the history list, parses it, and then executes it. The previous command typed is always saved. You can recall a command at any time from the history list and reexecute it without retyping the command. During a login session, the commands you type are appended to the history list until you exit, at which time they can be saved in a file in your home directory, called history [7]. The terms history list and history file can be somewhat confusing. The history list consists of the command lines currently held in the shell's memory. The history file, normally called .history, is the text file where those commands are saved for future use. The built-in variable, savehist, saves the history list to the .history file when you log out, and loads its contents into memory when you start up. (See -S and -L options to the history command in Table 10.2.) The history built-in command displays the history list. It supports a number of arguments to control how the history is displayed.

[7] The name of the.history file can be changed by assigning the new name to the histfile shell variable

Table 10.2. The history Command and Options
Option Meaning
-h Prints history list without numbers.
-T Prints timestamps in comment form.
-r Prints history list in reverse.
-S [filename] Saves history list to .history or filename if given.
-L [filename] Appends history file (.history or filename) to the history list.
-M [filename] Like -L, except merges contents of history file with current history list.
-c Clears the history list in memory, not the history file.
n n is a number, e.g., history 5, controlling the number of lines displayed.

Although the default name for the history file is .history, its name can be changed by assigning an alternative name to the built-in shell variable, histfile. The history shell variable is set to a number specifying how many commands to display and the histdup variable can be set so that duplicate entries are not added to the history file.

Example 10.15.
(The Command Line)
> history
						1 17:12   cd
						2 17:13   ls
						3 17:13   more /etc/fstab
						4 17:24   /etc/mount
						5 17:54   sort index
						6 17:56   vi index
					

Explanation

The history list displays the last commands that were typed at the command line. Each event in the list is preceded with a number (called an event number) and the time that it was entered at the command line.

The history Variable

The TC shell history variable can be set to the number of events from the history list that will be displayed on the terminal. Normally, this is set in the /etc/.cshrc or ~/.tcshrc file, the user's initialization file. It is set to 100 by default. You can also provide an optional second value for the history variable to control the way the history is formatted. This value uses the same formatting sequences as the prompt variable. (See Table 10.1.) The default format string for history is: %h %T %R .

Example 10.16.
1  set history=1000

2  set history= ( 1000 '%B%h %R
')

3  history
							136 history
							137 set history = ( 1000 '%B%h %R
' )
							138 history
							139 ls
							140 pwd
							141 cal
							141 pwd
							142 cd
						

Explanation

  1. The last 1000 commands typed at the terminal can be displayed on the screen by typing the history command.

  2. The last 1000 commands typed at the terminal are displayed. The format string causes the history list to be displayed in bold text (%B) first with the event number (%h), then a space, and finally the command that was typed (%R) at the command line followed by a newline ( .)

  3. When you type history, the new format is shown. This is only a selected section of the real history list.

Saving History and the savehist Variable

To save history events across logins, set the savehist variable. This variable is normally set in the .tcshrc file, the user's initialization file. If the first value assigned to savehist is a number, it cannot exceed the number set in the history variable, if the history variable is set. If the second value is set to merge, the history list is merged with the existing history file instead of replacing it. It is sorted by time-stamp, and the most recent events saved.

Example 10.17.
1  set savehist
2  set savehist = 1000
3  set savehist = 1000 merge
						

Explanation

  1. The commands from the history list are saved in the history file and will be at the top of the history list the next time you log in.

  2. The history file is replaced with the last 1000 commands from the history list, and saved. It will be displayed when you next log in.

  3. Rather than replacing the existing history file, the current history list will be merged with the existing history file when you log out, and loaded into memory after you log in.

Displaying History

The history command displays the events in the history list. The history command also has options that control the number of events and the format of the events that will be displayed. The numbering of events does not necessarily start at one. If you have 100 commands on the history list, and you have set the history variable to 25, you will only see the last 25 commands saved.

Example 10.18.
1  > set history = 10
2  > history
							1 ls
							2 vi file1
							3 df
							4 ps –eaf
							5 history
							6 more /etc/passwd
							7 cd
							8 echo $USER
							9 set
							10 ls
						

Explanation

  1. The history variable is set to 10. Only the last 10 lines of the history list will be displayed, even if there may be many more.

  2. The last 10 events from the history are displayed. Each command is numbered.

Example 10.19.
1  > history –h
							print without line numbers
							ls
							vi file1
							df
							ps –eaf
							history
							more /etc/passwd
							cd
							echo $USER
							set
							history –n

2  > history -c
						

Explanation

  1. With the h option, the history list is displayed without line numbers.

  2. With the c option, the history list is cleared.

Example 10.20.
> history –r
							# print the history list in reverse
							11 history –r
							10 history –h
							9 set
							8 echo $USER
							7 cd
							6 more /etc/passwd
							5 history
							4 ps –eaf
							3 df
							2 vi file1
							1 ls
						

Explanation

The history list is displayed in reverse order.

Example 10.21.
> history 5
							# prints the last 5 events on the history list
							7  echo $USER
							8  cd
							9  set
							10 history –n
							11 history 5
						

Explanation

The last five commands on the history list are executed.

Accessing Commands from the History File

There are several ways to access and repeat commands from the history list. You can use the arrow keys to scroll up and down the history list, and to move left and right across lines, editing as you go; you can use a mechanism called history substitution to reexecute and fix spelling mistakes; or you can use the built-in emacs or vi editors to retrieve, edit, and execute previous commands. We'll step through each of these procedures and then you can choose whatever way works best for you.

  1. The Arrow Keys

    To access commands from the history list, you can use the arrow keys on the keyboard to move up and down through the history list, and from left to right You can edit any of the lines in the history list by using the standard keys for deleting, backspacing, etc. As soon as you have edited the line, pressing the carriage return (Enter key) will cause the command line to be reexecute. You can also use standard emacs or vi commands to edit the history list. (See Table10.5 and Table10.6. The arrow keys behave the same way for both the vi and emacs keybindings. (See Table 10.3.)

    Table 10.3. The Arrow Keys
    Up arrow moves up the history list.
    Down arrow moves down the history list.
    Right arrow moves cursor to right of history command.
    Left arrow moves cursor to left of history command.

  2. Reexecuting and Bang! Bang!

    To reexecute a command from the history list, use the exclamation point (bang) to start history substitution. The exclamation point can begin anywhere on the line and can be escaped with a backslash. If the ! is followed by a space, tab, or newline, it will not be interpreted. There are a number of ways to use history substitution to designate what part of the history list you want to redo. (See Table 10.4.) If you type two exclamation points (!!), the last command is reexecuted. If you type the exclamation point followed by a number, the number is associated with the command from the history list and the command is executed. If you type an exclamation point and a letter, the last command that started with that letter is executed. The caret (^) is also used as a shortcut method for editing the previous command.

    After history substitution is performed, the history list is updated with the results of the substitution shown in the command. For example, if you type !! the last command will be reexecuted and saved in the history list in its expanded form. If you want the last command to be added to the history list in its literal form; i.e., !!, then set the histlit shell variable.

Example 10.22.
1  > date
							Mon Feb  8 12:27:35 PST 2000

2  > !!
							date
							Mon Aug  10 12:28:25 PST 2000

3  >  !3
							date
							Mon Aug  10 12:29:26 PST 2000

4  > !d
							date
							Mon Aug  10 12:30:09 PST 2000

5  > dare
							dare: Command not found.

6  > ^r^t
							date
							Mon Apr  10 16:15:25 PDT 2000

7  > history
							1 16:16  ls
							2 16:16  date
							3 16:17  date
							4 16:18  date
							5 16:18  dare
							6 16:18  date

8  > set histlit

9  > history
							1 16:18  ls
							2 16:19  date
							3 16:19  !!
							4 16:20  !3
							5 16:21  dare
							6 16:21  ^r^t
						

Explanation

  1. The Linux date command is executed at the command line. The history list is updated. This is the last command on the list.

  2. The !! (bang bang) gets the last command from the history list; the command is reexecuted.

  3. The third command on the history list is reexecuted.

  4. The last command on the history list that started with the letter d is reexecuted.

  5. The command is mistyped.

  6. The carets are used to substitute letters from the last command on the history list. The first occurrence of an r is replaced with a t.

  7. The history command displays the history list, after history substitution has been performed.

  8. By setting histlit, the shell will perform history substitution, but will put the literal command typed, on the history list; i.e., just as it was typed.

  9. When histlit is set, the output of the history command shows what commands were literally typed before history substitution took place. (This is just a demo; the history numbers are not accurate.)

Example 10.23.
1  % cat file1 file2 file3
							<Contents of files displayed here>

   > vi !:1
							vi file1

2  > cat file1 file2 file3
							<Contents of file, file2, and file3 are displayed here>

   > ls !:2
							ls file2
							file2

3  > cat file1 file2 file3
   > ls  !:3
							ls file3
							file3

4  > echo a b c
							a b c
   > echo !$
							echo c
							c

5  > echo a b c
							a b c
   > echo !^
							echo a
							a

6  > echo a b c
							a b c
   > echo !*
							echo a b c
							a b c

7  > !!:p
							echo a b c
						

Explanation

  1. The cat command displays the contents of file1 to the screen. The history list is updated. The command line is broken into words, starting with word number zero. If the word number is preceded by a colon, that word can be extracted from the history list. The !:1 notation means "get the first argument from the last command on the history list and replace it in the command string." The first argument from the last command is file1. (Word 0 is the command itself.)

  2. The !:2 is replaced with the second argument of the last command, file2, and given as an argument to ls. File2 is printed. (File2 is the third word.)

  3. ls !:3 reads " go to the last command on the history list and get the fourth word (words start at zero) and pass it to the ls command as an argument. " (File3 is the fourth word.)

  4. The bang (!) with the dollar sign ($) refers to the last argument of the last command on the history list. The last argument is c.

  5. The caret (^) represents the first argument after the command. The bang (!) with the ^ refers to the first argument of the last command on the history list. The first argument of the last command is a.

  6. The asterisk (*) represents all arguments after the command. The bang (!) with the * refers to all of the arguments of the last command on the history list.

  7. The last command from the history list is printed but not executed. The history list is updated. You could now perform caret substitutions on that line.

Table 10.4. Substitution and History
Event Designators Meaning
! Indicates the start of history substitution.
!! Reexecutes the previous command.
!N Reexecutes the N th command from the history list.
!-N Reexecutes the N th command back from present command.
!string Reexecutes the last command starting with string.
!?string? Reexecutes the last command containing string.
!?string?% Reexecutes the most recent command line argument from the history list containing.string.
!^ Uses the first argument of the last history command in the current command line.
!* Uses all of the arguments from the last history command in the current command line.
!$ Uses the last argument from the last history command in the current command line.
!! string Appends string to the previous command and executes.
!N string Appends string to N th command in history list and executes.
!N:s/old/new/ In previous N th command, substitutes the first occurrence of old string with new string.
!N:gs/old/new/ In previous N th command, globally substitutes old string with new string.
^old^new^ In last history command, substitutes old string with new string.
command !N:wn Executes current command appending an argument (wn) from the N th previous command. wn is a number starting at 0, 1, 2, … designating the number of the word from the previous command; word 0 is the command itself, and 1 is its first argument, etc.
!N:p Puts the command at the bottom of the history list and prints it, but doesn't execute it.

10.3.2. The Built-In Command Line Editors

The command line can be edited by using the same type of key sequences that you use in either the emacs or vi editors. You can use editor commands to scroll up and down the history list. Once the command is found, it can be edited, and by pressing the Enter key, reexecuted. When the shell was compiled, it was given a default set of keybindings for the emacs editor.

The bindkey Built-In Command

The built-in bindkey command is used to select either vi or emacs for command line editing and to list and set key bindings for the respective editors. To use vi as your command line editor, use bindkey with the -v option:

bindkey –v

and to go back to emacs:

bindkey –e

To see a list of editor commands and a short description of what each does, type:

bindkey –l

And to see the actual keys and how they are bound, type:

bindkey

To actually bind keys to commands, see "Binding Keys" .

The vi Built-In Editor

To edit the history list, go to the command line and press the ESC key. Then press the K key if you want to scroll upward in the history list, and the J key to move downward, just like standard vi motion keys. When you find the command that you want to edit, use the standard keys that you would use in vi for moving left and right, deleting, inserting, and changing text. See Table 10.5. After making the edit, press the Enter key. The command will be executed and added to the bottom of the history list. If you want to add or insert text, then use any of the insertion commands (i, e, o, O, etc.). Remember, vi has two modes: the command mode and the insert mode. You are always in the insert mode when you are actually typing text. To get back to the command mode, press the Escape key (ESC).

Table 10.5. vi Commands
Command Function
Moving Through the History File
ESC k or + Move up the history list.
ESC j or - Move down the history list.
G Move to first line in history file.
5G Move to fifth command in history file.
/string Search upward through history file.
? String search downward through history file.
Moving Around on a Line
h Move left on a line.
l Move right on a line.
b Move backward a word.
e or w Move forward a word.
^ or 0 Move to beginning of first character on the line.
$ Move to end of line.
Editing with vi
a A Append text.
i I Insert text.
dd dw x Delete text into a buffer (line, word, or character).
cc C Change text.
u U Undo.
yy Y Yank (copy a line into buffer).
p P Put yanked or deleted line down below or above the line.
r R Replace a letter or any amount of text on a line.

The emacs Built-In Editor

If you are using the emacs built-in editor, like vi, start at the command line. To start moving upward through the history file, press ^P. To move down, press ^N . Use emacs editing commands to change or correct text, then press Enter, and the command will be reexecuted. See Table 10.6.

Table 10.6. emacs Commands
Command Function
Ctrl-P Move up history file.
Ctrl-N Move down history file.
ESC < Move to first line of history file.
ESC > Move to last line of history file.
Ctrl-B Move backward one character.
Ctrl-R Search backward for string.
ESC B Move back one word.
Ctrl-F Move forward one character.
ESC F Move forward one word.
Ctrl-A Move to the beginning of the line.
Ctrl-E Move to the end of the line.
ESC < Move to the first line of the history file.
ESC > Move to the last line of the history file.
Editing with emacs
Ctrl-U Delete the line.
Ctrl-Y Put the line back.
Ctrl-K Delete from cursor to the end line.
Ctrl-D Delete a letter.
ESC D Delete one word forward.
ESC H Delete one word backward.
ESC space Set a mark at cursor position.
Ctrl-X Ctrl-X Exchange cursor and mark.
Ctrl-P Ctrl-Y Push region from cursor to mark into a buffer (Ctrl-P) and put it down (Ctrl-Y).

Binding Keys

The bindkey built-in command lists all the standard keybindings including keybindings for emacs and vi. The keybindings are divided up into four groups: the standard key bindings, alternative key bindings, multicharacter key bindings, and the arrow key bindings. The bindkey command also allows you to change the current bindings of keys.

Example 10.24.
1  > bindkey
							Standard key bindings
							"^@"           ->  is undefined
							"^A"           ->  beginning-of-line
							"^B"           ->  backward-char
							"^C"           ->  tty-sigintr
							"^D"           ->  list-or-eof
							"^E"           ->  end-of-line
							"^F"           ->  forward-char
							"^L"           ->  clear-screen
							"^M"           ->  newline
							…      ….
							Alternative key bindings
							"^@"           ->  is undefined
							"^A"           ->  beginning-of-line
							"^B"           ->  is undefined
							"^C"           ->  tty-sigintr
							"^D"           ->  list-choices
							"^E"           ->  end-of-line
							"^F"           ->  is undefined
							……     …..
							Multi-character bindings
							"^[[A"         -> up-history
							"^[[B"         -> down-history
							"^[[C"         -> forward-char
							"^[[D"         -> backward-char
							"^[OA"         -> up-history
							"^[OB"         -> down-history
							…    ….
							Arrow key bindings
							down           -> down-history
							up             -> up-history
							left           -> backward-char
							right          -> forward-char
						

The -l option to bindkey lists the editor commands and what they do. See Example 10.25.

Example 10.25.
> bindkey  -l
backward-char
          Move back a character
backward-delete-char
          Delete the character behind cursor
backward-delete-word
          Cut from beginning of current word to cursor - saved in cut
          buffer
backward-kill-line
          Cut from beginning of line to cursor - save in cut buffer
backward-word
          Move to beginning of current word
beginning-of-line
          Move to beginning of line
capitalize-word
          Capitalize the characters from cursor to end of current
          word
change-case
          Vi change case of character under cursor and advance one
          character
change-till-end-of-line
          Vi change to end of line
clear-screen
Standard key bindings
           …..    …

The bindkey command can also display the values for individual key bindings as shown in Example 10.26. The emacs mappings are shown by default, but with the -a option to bindkey, the alternate mappings for vi keys are displayed. The arguments to bindkey are specified as a sequence of special characters to represent the key sequences followed by the editing command key to which the key will be bound. You can bind keys not only to emacs orvi editor commands, but also to Linux commands and strings.

Table 10.7. Keybinding Characters
Characters Meaning
^C Control-C
^[ ESC
^? DEL
a Control-G (bell)
 Control-H (backspace)
e ESC (escape)
f Formfeed
Newline
Return
Tab
v Control-K (vertical tab)
nn ASCII octal number

Example 10.26.
1  > bindkey ^L
   "^L"      ->     clear-screen

2  > bindkey ^C
   "^C"      ->     tty-sigintr

3  > bindkey "j"
   "j"       ->     self-insert-command

4  > bindkey -v

5  > bindkey -a "j"
   "j"       ->     down-history

Explanation

  1. The bindkey command with a Control key (^L) displays to what command the control key is bound. ^L causes the screen to be cleared.

  2. Control-C (^C) is bound to the interrupt signal, which normally terminates a process.

  3. Lowercase "j" is an emacs self-insert-command which does nothing but insert that letter into the buffer.

  4. In order to see the alternate vi key bindings, be sure you have set the vi command line editor with: bindkey -v as shown here.

  5. With the - a option, bindkey displays the alternate key mapping for "j"; i.e., the vi key for moving down the history list.

Example 10.27.
1  > bindkey "^T" clear-screen

2  > bindkey "^T"
   "^T"      ->     clear-screen

3  > bindkey -a "^T"
   "^T"      ->     undefined-key

4  > bindkey -a
							[Control-v Control t] clear-screen
         Press keys one after the other

5  > bindkey -a [Control-v Control t]
   "^T"       ->     clear-screen

6  > bindkey -s'ehi'  'Hello to you!
'
   > echo [Esc]hi    Press escape followed by 'h' and 'i'
     Hello to you!
   >
7  > bindkey'^[hi'
   "^[hi"    ->   "Hello to you!"

8  > bindkey -r'[hi'

9  > bindkey'ehi'
   Unbound extended key "^[hi"

10 > bindkey -c'ex''ls | more'
						

Explanation

  1. Control-T is bound to the command to clear the screen, a default emacs key mapping. This key sequence was not originally bound to anything. Now when the Control and T keys are pressed together, the screen will be cleared.

  2. The bindkey command, with the key sequence as an argument, will display the mapping for that sequence, if there is one.

  3. With the -a option and a key sequence, bindkey displays the value of the alternate key map, vi. In this example, bindkey with the -a option and the key sequence shows that the alternate mapping (vi) does not have this sequence bound to anything.

  4. With the -a option, bindkey can bind keys to the alternate key map, vi. By pressing Control-V followed by Control-T, the key sequence is created and assigned the value clear-screen. Control-V/Control-T can also be represented as "^T" as shown in the previous example.

  5. The bindkey function displays the alternate mapping for ^T and its command.

  6. With the -s command, bindkey will bind a literal string to a key sequence. Here the string "Hello to you! " is bound to the escape sequence hi. By pressing the ESC key and then an h and an i, the string will be sent to standard output.

  7. The bindkey command displays the binding for the escape sequence hi. The ^[ is another way to represent ESC (escape).

  8. With the -r option, bindkey removes a key binding.

  9. Because the key binding was removed, the output says that this extended key sequence is not bound.

  10. With the -c option, bindkey can bind a key sequence to a Linux command. In this example, pressing the Escape key, followed by the "x" key will cause the command ls to be piped to more.

Table 10.8. bindkey Options
bindkey Lists All Key Bindings
bindkey -a Allow alternate key mapping.
bindkey -d Restore default bindings.
bindkey -e Use emacs bindings.
bindkey -l Display all editing commands and what they mean.
bindkey -u Display usage message.
bindkey -v Use vi key bindings.
bindkey key Display binding for key.
bindkey key command Bind key to emacs or vi command.
bindkey -c key command Bind key to UNIX/Linux command.
bindkey -s key string Bind key to string.
bindkey -r key Remove key binding.

10.3.3. Command, Filename, and Variable Completion

To save typing, tcsh has a mechanism called completion that allows you to type part of a command, filename, or variable, and then by pressing the Tab key, have the rest of the word completed for you.

If you type the first few letters of a command, and press the Tab key, tcsh will attempt to complete the command name. If tcsh cannot complete the command, because it doesn't exist, the terminal will beep and the cursor will stay at the end of the command. If there is more than one command starting with those characters, by pressing Control-D, all commands that start with those characters will be listed.

Filename and variable completion work the same as command completion. With filename completion, if there are several files starting with the same letters, tcsh will complete the shortest name that matches, expand out the filename until the characters differ, and then flash the cursor for you to complete the rest. See Example 10.28.

The autolist Variable

If the autolist variable is set, and there are a number of possible completions, all of the possible commands, variables, or filenames will be listed depending on what type of completion is being performed when the tab key is entered.

Example 10.28.
1  > ls
							file1 file2 foo foobarckle fumble

2  > ls fu[tab]   expands to filename to
							fumble

3  > ls fx[tab]   terminal beeps, nothing happens

4  > ls fi[tab]   expands to
							file_
							(_ is a cursor)

5  > set autolist

6  > ls f[tab]     lists all possibilities
							file1 file2 foo foobarckle fumble

7  > ls foob[tab] expands to
							foobarckle

8  > da[tab]      completes the
							date
							command
							date
							Fri Aug 9 21:15:38 PDT 2000

9  > ca[tab]      lists all commands starting with
							ca
							cal    captoinfo   case   cat

10 > echo $ho[tab]me   expands shell variables
							/home/ellie/

11 > echo $h[tab]
							history home
						

Explanation

  1. All files are listed for the current working directory.

  2. After fu is typed, the Tab key is pressed, causing the filename to be completed to fumble, and listed.

  3. Because none of the files start with fx, the terminal beeps and the cursor remains but does nothing.

  4. There are a number of files starting with fi; the filenames are completed until the letters are no longer the same. When you press Control-D, all files with that spelling are listed.

  5. The autolist variable is set. If there are a number of choices, when you press the Tab key, autolist displays all the possibilities.

  6. After you press the Tab key, a list of all files beginning with f are printed.

  7. When the Tab key is pressed, the filename is expanded to foobarckle.

  8. When the Tab key is pressed after da, the only command that begins with da is the date command. The command name is expanded and executed.

  9. Because autolist is set, when the Tab key is pressed after ca, all commands starting with ca are listed. If autolist is not set, type Control-D to get a list.

  10. The leading $ on a word indicates that the shell should perform variable expansion when the Tab key is pressed to complete the word. The variable home is completed.

  11. Variable completion is ambiguous in this example. When completion is attempted by pressing the Tab key, all possible shell variables are listed.

The fignore Variable

The shell variable, fignore, can be set to ignore certain filename extensions when filename completion is in use. For example, you may not want to expand files that end in .o because they are unreadable object files. Or maybe you don't want the .gif files to be accidently removed when filenames are expanded. For whatever reason, the fignore variable can be assigned a list of extensions for files that will be excluded from filename expansion.

Example 10.29.
1  > ls
							baby       box.gif   file2    prog.c
							baby.gif   file1     file3    prog.o

2  > set fignore = (.o .gif )

3  > echo ba[tab]      Completes baby but ignores baby.gif
							baby

4  > echo box[tab].gif    fignore is ignored if only one completion
							box.gif
							is possible

5  > vi prog[tab]      expands to prog.c
							Starts vi with prog.c as its argument
						

Explanation

  1. The files in the current working directory are listed. Note that some of the files have extensions on their names.

  2. The fignore variable allows you to list those filename extensions that should be ignored when filename completion is performed. All filenames ending in either .o or .gif will be ignored.

  3. By pressing the Tab key, only the file, baby, is listed, not baby.gif. The .gif files are ignored.

  4. Even though .gif is listed as a suffix to be ignored, fignore will not take effect when there are no other possible completions, such as the same filename without the .gif extension as in line 3.

  5. When the vi editor is invoked, prog is expanded to prog.c.

The complete Shell Variable

This is a variable that does a lot! It is a little tricky trying to decipher all it can do from the tcsh man page, but you may find some of these examples helpful for a start. You can control what kind of completion you are doing. For example maybe you only want completion to expand directory names, or a filename depending on its position in the command line, or maybe you would like certain commands to be expanded and others excluded, or even create a list of possible words that can be expanded. Whatever it is you want to do with completion, no doubt, the complete shell variable will accommodate you.

Filename completion can be even more sophisticated if the complete shell variable is set to enchance. This causes tab completion to ignore case; to treat hyphens, periods, and underscores as word separators; and to consider hyphens and underscores as equivalent.

Example 10.30.
1   > set complete=enchance

2   > ls g..[tab]   expands to gawk-3.0.3
							gawk-3.0.3

3   > ls GAW[tab]   expands to gawk-3.0.3
							gawk-3.0.3
						

Explanation

  1. By setting the complete shell variable to enchance, tab completion will ignore case; will treat hyphens, periods, and underscores as word separators; and will consider hyphens and underscores as equivalent.

  2. With enhance set, filename completion expands g.. to any files starting with a g, followed by any two characters (..), and any characters to complete the filename, including hyphens, periods, etc.

  3. With enhance set, filename completion expands GAW to any files starting with GAW, where GAW can be any combination of upper and lowercase letters, and the remaining characters can be any characters even if they contain hyphens, periods, and underscores.

Programming Completions

To customize completions to a more specific functionality, you can program the completions, and then store them in the ~/.tcshrc file, making them part of your tcsh environment each time you start a new TC shell. The purpose of programming completions is to improve efficiency and select types of commands and arguments that will be affected. (The Tab key for word completion, and Control-D to list possible completions still work the same way as they did for simple completions.)

Types of Completions

There three types of completions: p, n, and c. A p -type completion is position-dependent. It rules the way a completion is performed based on the position of a word in the command line, where position 0 is the command, position 1 is the first argument, position 2, the second argument, etc. Suppose, for example, you wanted to guarantee that any time a completion is performed for the built-in cd command, the first (and only) argument to cd is completed only if it is a directory name, nothing else; then you can program the completion as shown in the following example:

complete  cd   'p/1/d/'

The complete command is followed by the cd command and what is called the completion rule. The p stands for the word position in the command line. The command, cd, is position 0 and its first argument is position 1. The pattern part of the rule is enclosed in slashes (p/1/ means position 1, the first argument to cd), and will be affected by the completion rule. The d part of the pattern is called a word type. See Table 10.9 for a complete list of word types. The d word type means that only directories are to be affected by the completion. A filename or alias, for example, would not be completed if given as the first argument to cd. The rule states that whenever tab completion is performed on the cd command, it will only take place if the first argument is a directory, and Control-D will only list directories if the match is ambiguous; i.e., there is more than one possible completion. See Example 10.31 for p -type completions.

Example 10.31.
							# p-type completions (positional completion)

1  > complete
							alias     'p/1/a/'
							cd        'p/1/d/'
							ftp       'p/1/( owl ftp.funet.fi prep.ai.mit.edu)'
							man       'p/*/c/'

2  > complete  vi'p/*/t/'

3  > complete vi
							vi 'p/*/t/'

4  > set autolist

5  > man fin[tab]    Completes command names
							find      find2perl   findaffix  findsmb  finger

6  > vi b[tab]       Completes only  filenames, not directories
							bashtest binded bindings bindit

7  > vi na[tab]mes

8  > cd sh[tab]ellsolutions/

9  > set hosts = ( netcom.com 192.100.1.10 192.0.0.200 )

10 > complete telnet 'p/1/$hosts/'

11 > telnet net[tab]com.com
							telnet netcom.com

12 > alias m[tab]    Completes alias names
							mc mroe mv

13 > ftp prep[tab]
						

Explanation

  1. The complete built-in command, without arguments, lists all programmed completions. The following examples (lines 2 through 11) use these completion rules.

  2. This rule states that if tab completion is used when typing arguments to the vi command, that all arguments (*), must be of type "t" (i.e., plain text files) for completion to performed.

  3. The complete command, with the name of a command as its argument, displays the completion rule for that command. The completion rule for vi is displayed.

  4. By setting the built-in command, autolist, all possible tab completions will automatically be printed. (You don't have to press Control-D.)

  5. The man command has a programmed completion: complete man `p/1/c/'. This rule states that the first argument given to the man command must be a command, because c is defined as a command word type. In this example, completion is attempted with the letters fin as the argument to man. All manual commands starting with fin will be displayed.

  6. Only filenames will be completed, because the vi editor completion was programmed to complete only text files, not directories.

  7. According to the vi completion rule, only text filenames will be completed, no matter how many arguments are passed.

  8. When filename completion is performed on the first argument to the built-in cd command, the only word that will be completed must be the name of a directory as stated in the completion rule. The argument in this example will expand to a directory called shellsolutions.

  9. The variable hosts is set to a list of IP addresses or hostnames.

  10. The completion rule for telnet states that completion will be performed if position 1 contains one of the hostnames set in the hosts variable. This is a list word type completion.

  11. The telnet command is executed and the word beginning with net, followed by pressing the Tab key, is completed to netcom.com, which is one of the hostnames in the hosts variable, previously set.

  12. The alias completion is performed if the user types the word alias followed by a word that will be expanded to all aliases that contain that word. Word type a means only aliases are expanded for p, postition 1.

Table 10.9. Completion Word Types
Word Type
a alias
b editor key-binding commands
c commands (built-in or external commands)
C external commands which begin with the supplied path prefix
d directory
D directories which begin with the supplied path prefix
e environment variables
f filenames (not directory)
F filenames which begin with the supplied path prefix
g groupnames
j jobs
l limits
n nothing
s shell variables
S signals
t plain ("text") files
T plain ("text") files beginning with the supplied path prefix
v any variables
u usernames
X command names for which completions have been defined
x like n, but prints a message if ^D is typed
C, D, F, T like c, d, f, t, but selects completions from a given directory
(list) selects completions from words in a list

A c -type completion is used to complete a pattern in the current word. The current word refers to the pattern enclosed in forward slashes. It rules that if the pattern is matched, any completion performed will finish the pattern.

Example 10.32.
							# c-type completions

1  > complete
							stty     'c/-/(raw xcase noflsh)/'
							bash     'c/-no/(profile rc braceexpansion)/'
							find     'c/-/(user name type exec)/'
							man      'c/perl/(delta faq toc data modlib locale)/'

2  > stty -r[tab]aw
							stty -raw

3  > bash -nop[tab]rofile
							bash -noprofile

4  > find / -n[tab]ame
							.tcshrc-p[tab]rint
							find / -name .tcshrc -print

5  >  man perlde[tab]lta
							man perldelta

6  > uncomplete stty
   > complete
							bash     'c/-no/(profile rc braceexpansion)/'
							find     'c/-/(user name type exec)/'
							man      'c/perl/(delta faq toc data modlib locale)/'

7  >  uncomplete *
						

Explanation

  1. These examples demonstrate a c -type completion. If the pattern in the first set of forward slashes is typed, that pattern will be completed by one of the words listed in the parentheses when a character(s) from that list is typed, followed by the Tab key.

  2. When the stty command is typed, followed by a dash (-) character, the word will be completed to -raw, if a dash, an r, and the Tab key are entered. One of the words from the rule list in parentheses (raw xcase noflsh) can be completed.

  3. When the bash command is typed, followed by the pattern, -no, that pattern will be completed to -noprofile, if the pattern -no is followed by a p and the Tab key. Completion is performed from one of the words in the rule list (profile rc braceexpansion); in this example, resulting in -noprofile.

  4. Arguments to the find command are completed if the dash (-) character is completed by typing significant characters from any of the words in the find rule list (user name type exec).

  5. When the man command is typed, the pattern perl is completed to perldelta since the pattern is followed by one of the words from the list (delta faq toc data modlib locale).

  6. The uncomplete built-in command removes the completion rule for stty. The other completion rules remain.

  7. The uncomplete built-in command, with the asterisk as its argument, removes all completion rules.

N -type completions match the first word and complete the second one.

Example 10.33.
# n-type completions (next word completion)
1  > complete
							rm   'n/-r/d/'
							find 'n/-exec/c/'

2  > ls -ld testing
							drwxr-sr-x  2  ellie  root   1024 Aug 29 11:02 testing

3  > rm -r te
							[tab]sting
						

Explanation

  1. These examples demonstrate an n -type completion. If the word in the first set of forward slashes is typed (the current word) and matched, the next word (in the second set of forward slashes) will be completed according to the word type. The complete command lists two n -type completions, one for the rm command and one for the find command. When the rm command is executed with the -r switch, the word following -r must be of type directory if completion is to be performed. The rule for the find command is: if the -exec option is given, any words following it must be commands if completion is to be performed.

  2. The output of the ls command shows that testing is a directory.

  3. Filename completion is successful for the rm command because word completion is attempted for a directory named testing. If testing were a plain file, the completion would not have been performed.

10.3.4. Manipulating the Directory Stack

If you find that as you work, you cd up and down the directory tree into many of the same directories, you can make it easy to access those directories by pushing them onto a directory stack and manipulating the stack. The directory stack is often compared to stacking trays in a cafeteria where the trays are stacked on top of each other, the first one being at the bottom of the stack. The pushd built-in command pushes directories onto a stack and the popd command removes them. (See following Examples.) The stack is a numbered list of directories with the top directory being the most recent directory pushed onto the stack. The directories are numbered starting with the top directory at 0, the next one numbered 1, etc. The built-in command, dirs, with a -v option, displays the numbered directory stack.

The pushd and popd Commands

The pushd command with a directory as an argument causes the new directory to be added to the directory stack and, at the same time, changes to that directory. If the argument is a dash (-), the dash refers to the previous working directory. If the argument is a + and a number (n), pushd extracts the n th directory from the stack and pushes it onto the top, then changes to that directory. Without arguments, pushd exchanges the top two elements of the directory stack, making it easy to switch back and forth between directories. There are a number of shell variables that control the way pushd works. (See Setting Local Variables.)

To save a directory stack across login sessions, you must set the savedirs variable in one of the tcsh initialization files (e.g., ~/.tcshrc). The directory stack will be stored in a file called ~/.cshdirs and will be automatically sourced when the shell starts up.

The popd command removes a directory from the top of the stack, and changes to that directory.

Table 10.10. Directory Stack Variables
pushdtohome If set, pushd without arguments, is same as pushd ~ or cd.
dunique Before pushing a directory onto the stack, removes any directories with the same name.
pushdsilent Doesn't print the directory stack when pushd is executed.
deextract If set, pushd +n extracts the n th directory from the directory stack before pushing it onto the stack.
pushtohome Without arguments, pushes to ~, the user's home directory.
dirsfile Can be assigned a filename where the directory stack can be saved across logins.
savedirs Saves the directory stack across logins.
dirstack Used to display the stack or assign directories to it.

Example 10.34.
1  > pwd
							/home/ellie

   > pushd ..
							/home ~

   > pwd
							/home

2  > pushd
							# swap the two top directories on the stack
							~ /home

   > pwd
							/home/ellie

3  > pushd perlclass
							~/perlclass  ~  /home

4  > dirs -v
							
								
									
								
							
							0      ~/perlclass
							1      ~
							2      /home

5  >popd
							~      /home
   > pwd
							/home/ellie

6  > popd
							/home

   > pwd
							/home

7  > popd
							popd: Directory stack empty.
						

Explanation

  1. First the pwd command displays the present working directory, /home/ellie. Next the pushd command with .. as its argument, pushes the parent directory (..) onto the directory stack. The output of pushd indicates that /home is at the top of the directory stack and the user's home directory (~), /home/ellie, is at the bottom of the stack. pushd also changes the directory to the one that was pushed onto the stack; i.e.,.. which translates to /home. The new directory is displayed with the second pwd command.

  2. pushd, without arguments, exchanges the two top directory entries on the stack and changes to the swapped directory; in this example, the directory is switched back to the user's home directory, /home/ellie.

  3. The pushd command will push its argument, ~/perlclass, onto the stack, and change to that directory.

  4. The built-in dirs command displays the numbered directory stack, with 0 being the top level. See the directory stack chart on the right side of Example 10.34.

  5. The popd command removes a directory from the top of the stack, and changes to that directory.

  6. The popd command removes another directory from the top of the stack, and changes to that directory.

  7. The popd command cannot remove any more directory entries because the stack is empty, and issues an error message saying so.

10.3.5. Spelling Correction

Spelling correction, a feature added to the TC shell, is the ability to correct spelling errors in filenames, commands, and variables. If using the emacs built-in editor, the spelling error can be corrected by using the spelling correction keys, bound to the Meta-s or Meta-S keys (use the ALT or ESC key if you don't have Meta) and Meta-$ to correct an entire line. The value of the prompt, prompt3, displays the spelling correction prompt.[8]

[8] From the tesh man page:"Beware: Spelling correction is not guaranteed to work the way one intends, and is provided as an experimental feature. Suggestions and improvements are welcome."

If you are using the vi built-in editor, set the built-in variable correct, and the shell will prompt you to fix the spelling.

Example 10.35.
1  >  fimger[Alt-s]    Replaces fimger with finger

2  > set correct=all

3  > dite
						CORRECT>date (y|n|e|a)? yes
						Wed Aug 11 19:26:27 PDT 2000

4  > dite
						CORRECT>date (y|n|e|a)? no
						dite: Command not found.
   >

5  > dite
						CORRECT>date (y|n|e|a)? edit
   > dite
						Waits for user to edit and then executes command

6  > dite
						CORRECT>date (y|n|e|a)? abort
   >

Explanation

  1. By pressing the Meta (or ALT or ESC) key together with an s, the spelling of a command, filename, or variable can be corrected. This does not work if you are using the built-in vi editor.

  2. By setting correct to all, tcsh will attempt to correct all spelling errors in the command line. This feature is available for both emacs and vi keybindings.

  3. Because the command was incorrectly spelled, the third prompt, prompt3, "CORRECT>date (y|n|e|a)?" appears on the screen, and the user is supposed to type the letter y if he wants the spelling corrected, an n if he doesn't, an e if he wants to edit the line himself, or an a if he wants to abort the whole operation.

  4. If the user wants the command to be unchanged, he types an n for no.

  5. If the user wants to edit the correction, he types an e, and he will be prompted to fix or enhance the command himself.

  6. If the correction is incorrect or not wanted, the user types an a, and the spelling correction is aborted.

Table 10.11. The correct Variable Arguments
Argument What It Does
cmd spell-corrects commands
complete completes commands
all spell-corrects entire command line

10.3.6. Aliases

An alias is a TC shell user-defined abbreviation for a command. Aliases are useful if a command has a number of options and arguments or the syntax is difficult to remember. Aliases set at the command line are not inherited by subshells. Aliases are normally set in the .tcshrc file. Because the .tcshrc is executed when a new shell is started, any aliases set there will get reset for the new shell. Aliases may also be passed into shell scripts but will cause potential portability problems, unless they are directly set within the script.

The TC shell has some additional preset aliases, which remain undefined until you define them. They are: beepcmd, cwdcmd, periodic, and precomd. These aliases are listed and defined in "Special Aliases (tcsh Only)" .

Listing Aliases

The alias built-in command lists all set aliases. The alias is printed first, followed by the real command or commands it represents.

Example 10.36.
> alias
							apache $   HOME/apache/httpd -f $ HOME/apache/conf/httpd.conf
							co     compress
							cp     cp –i
							ls1    enscript –B –r –Porange –f Courier8 !* &
							mailq  /usr/lib/sendmail –bp
							mc     setenv MC `/usr/bin/mc -P !*`; cd $MC; unsetenv MC
							more   more
							mv     mv –i
							uc     uncompress
							uu     uudecode
							vg     vgrind –t –s11 !:1 | lpr –t
							weekly (cd /home/jody/ellie/activity; ./weekly_report; echo
							Done)
						

Explanation

The alias command lists the alias (nickname) for the command in the first column and the real command the alias represents in the second column.

Creating Aliases

The alias command is used to create an alias. The first argument is the name of the alias, the nickname for the command. The rest of the line consists of the command or commands that will be executed when the alias is executed. Multiple commands are separated by a semicolon, and commands containing spaces and metacharacters are surrounded by single quotes.

Format

alias
alias aliasname command
alias aliasname 'command command(s)'
unalias aliasname

Example 10.37.
1  > alias m more
2  > alias mroe more
3  > alias lf ls-F
4  > alias cd' cd !*; set prompt = "%/ > " '
5  > cd ..
6  /home/jody  >  cd /
							# new prompt displayed
   / >

7  > set tperiod = 60
   > alias periodic 'echo You have worked an hour, nonstop'
8  > alias Usage' echo "Error: !* " ; exit 1'
						

Explanation

  1. The nickname for the more command is set to m.

  2. The alias for the more command is set to mroe. This is handy if you can't spell.

  3. The alias lf is a nickname for the tcsh built-in command ls-F. It lists files like ls -F, but is faster.

  4. When cd is executed, the alias for cd will cause cd to go to the directory named as an argument and will then reset the prompt to the current working directory (%/) followed by the string “>“. The !* is used by the alias in the same way it is used by the history mechanism. The backslash prevents the history mechanism from evaluating the !* first before the alias has a chance to use it. The !* represents the arguments from the most recent command on the history list. The alias definition is enclosed in quotes because of the white space.

  5. After the cd command changes to the parent directory, the prompt is expanded to the current working directory (%/) and a > symbol.[a]

    [a] If using /bin/csh as your shell, replace%with$cwd when setting the prompt.

  6. The new directory is /home/jody which is reflected in the prompt; after changing directory to root (/), the prompt again reflects the change.

  7. The tperiod variable is set to 60 minutes.The alias, periodic, is a preset alias. Every 60 minutes, the echo statement will be displayed.

  8. This alias is useful in scripts to produce a diagnostic message and to then exit the script. For an example of this alias in use, see Example 11.29.

Deleting Aliases

The unalias command is used to delete an alias. To temporarily turn off an alias, precede the alias name by a backslash.

Example 10.38.
1  > unalias mroe
2  > cd ..
						

Explanation

  1. The unalias command deletes the alias mroe from the list of defined aliases.

  2. The alias cd is temporarily turned off for this execution of the command only.

Alias Loop

An alias loop occurs when an alias definition references another alias that references back to the original alias.

Example 10.39.
1  > alias m more
2  > alias mroe m
3  > alias m mroe
							# Causes a loop
4  > m datafile
							Alias loop.
						

Explanation

  1. The alias is m. The alias definition is more. Every time m is used, the more command is executed.

  2. The alias is mroe. The alias definition is m. If mroe is typed, the alias m is invoked and the more command is executed.

  3. This is the culprit. If alias m is used, it invokes alias mroe, and alias mroe references back to m, causing an alias loop. Nothing bad happens. You just get an error message.

  4. Alias m is used. It is circular. M calls mroe and mroe calls m, then m calls mroe, etc. Rather than looping forever, the TC shell catches the problem and displays an error message.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.4.191