CHAPTER 5 Shells
You can use the history and savehist variables to set the number of previously executed commands to keep track of in this shell and how many to retain between logins, respectively. You could put a line such as the following in .cshrc to save the last 100 commands in this shell and the last 50 through the next login.
set history=100 savehist=50
The shell keeps track of the history list and saves it in ~/.history between logins.
You can use the built-in history command to recall previous commands, e.g. to print the last 10:
% history 10
52 cd workshop
53 ls
54 cd unix_intro
55 ls
56 pwd
57 date
58 w
59 alias
60 history
61 history 10
You can repeat the last command by typing !!:
% !!
53 ls
54 cd unix_intro
55 ls
56 pwd
57 date
58 w
59 alias
60 history
61 history 10
62 history 10
You can repeat any numbered command by prefacing the number with a !, e.g.:
% !57
date
Tue Apr 9 09:55:31 EDT 1996
Or repeat a command starting with any string by prefacing the starting unique part of the string with a !, e.g.:
% !da
date
Tue Apr 9 09:55:31 EDT 1996
When the shell evaluates the command line it first checks for history substitution before it interprets anything else. Should you want to use one of these special characters in a shell command you will need to escape, or quote it first, with a \ before the character, i.e. \!. The history substitution characters are summarized in the following table.
Command | Substitution Function |
---|---|
!! | repeat last command |
!n | repeat command number n |
!-n | repeat command n from last |
!str | repeat command that started with string str |
!?str? | repeat command with str anywhere on the line |
!?str?% | select the first argument that had str in it |
!: | repeat the last command, generally used with a modifier |
!:n | select the nth argument from the last command (n=0 is the command name) |
!:n-m | select the nth through mth arguments from the last command |
!^ | select the first argument from the last command (same as !:1) |
!$ | select the last argument from the last command |
!* | select all arguments to the previous command |
!:n* | select the nth through last arguments from the previous command |
!:n- | select the nth through next to last arguments from the previous command |
^str1^str2^ | replace str1 with str2 in its first occurrence in the previous command |
!n:s/str1/str2/ | substitute str1 with str2 in its first occurrence in the nth command, ending with a g substitute globally |
Additional editing modifiers are described in the man page.