CONTENTS |
An interactive shell is one in which the standard input, output, and errors are connected to a terminal. When using the TC[1] shell (tcsh) interactively, you will type commands at the tcsh prompt and wait for a response. The TC shell is a program that starts up at login and interprets commands. It is a public domain enhanced version of its predecessor, the Berkeley UNIX C shell. Added features include command line editing, fancy prompts, programmable completions (filenames, commands, and variables), spelling correction, etc.
The primary tcsh source distribution is at ftp.astron.com, also ftp.gw.com, and ftp.primate.wisc.edu.[2] Although tcsh is included in most Linux distributions, it can be ported to a number of operating systems, including Solaris, Windows NT, HP-UX, QNX, etc.
This chapter focuses on how to use the TC shell interactively and how to set up your initial working environment. The enhancements over the Berkeley C shell are extensive when working with the shell interactively, as you will see in this chapter. However, when used as a programming language, tcsh and csh are practically identical. Please refer to Chapter 10 for script writing with tcsh. The only change will be that where you see /bin/csh, you will use /bin/tcsh.
To find out what version of tcsh you are using, type at the shell prompt:
which tcsh
To tell you in what directory tcsh is installed (normally /bin), and to print the version information, type the following:
/directory_path/tcsh -c 'echo $version'
1 which tcsh /bin/tcsh 2 /bin/tcsh -c 'echo $version' tcsh 6.09.09 (Astron) 1998-08-16 (sparc-sun-solaris) options 8b,nls,dl,al,rh,color
Before the TC shell displays a prompt, it is preceded by a number of processes. See Figure 13.1.
After the system boots, the first process to run is called init, process identification number (PID) 1. It spawns a getty process. These processes are responsible for opening up the terminal ports, for providing a place where input comes from (stdin) and where standard output (stdout) and error (stderr) go, and for putting a login prompt on your screen. After the user types his user name, the /bin/login program is executed. The login program prompts for a password, encrypts and verifies your password, sets up an initial working environment, and then initiates the shell, /bin/tcsh. The TC shell looks in the /etc directory for a system startup file called /etc/csh.cshrc and /etc/csh.login (if it exists). It then looks in the user's home directory for a file called ~/.tcshrc, another initialization file used to customize the tcsh environment. If that file is not found, it will look for another file that does the same job, called ~/.cshrc (normally invoked when running csh). After executing commands in the .tcshrc file (or .cshrc), it will execute the history file, commonly called .history. Then commands in the ~/.login file are executed, and finally the .cshdirs file is executed. Each of these files will be explained in "The TC Shell Environment".[3]
The /etc/csh.cshrc and ~/.tcshrc files will be executed every time a new TC shell is started. The .login file is executed only once when the user logs on, and also contains commands and variables to initialize the user's environment. After executing commands from all the startup files, the prompt (> is the default) appears on your screen and the tcsh awaits commands. See Figure 13.2.
When logging out, the user presses Control-D or will be automatically logged out if the autologout shell variable has been set. Before logging off, the shell looks for a file called /etc/csh.logout or ~/.logout in the home directory and if either is located, its commands will be executed. The .logout file normally contains commands to clean up temporary files, append data to logfiles, wish the user a good day, etc.
After the tcsh program starts, it is programmed to execute a systemwide startup file, /etc/csh.cshrc, and then two shell initialization files in the user's home directory: the .tcshrc file and then the .login file. These files allow users to initialize their own environment.
# /etc/csh.cshrc # Systemwide environment and startup programs for csh users 1 if ($?PATH) then 2 setenv PATH "${PATH}:/usr/X11R6/bin" else 3 setenv PATH "/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin" endif 4 if ($?prompt) then 5 [ "$SHELL" = /bin/tcsh ] 6 if ($status == 0) then 7 set prompt='[%n@%m %c]$ ' 8 else 9 set prompt=\['id -nu'@'hostname -s'\]\$\ 10 endif endif 11 limit coredumpsize 1000000 12 [ 'id -gn' = 'id -un' -a 'id -u' -gt 14 ] 13 if $status then 14 umask 022 else 15 umask 002 endif 16 setenv HOSTNAME '/bin/hostname' 17 set history=1000 18 test -d /etc/profile.d 19 if ($status == 0) then 20 set nonomatch 21 foreach i ( /etc/profile.d/*.csh ) 22 test -f $i if ($status == 0) then 23 source $i endif end 24 unset nonomatch endif
EXPLANATION
|
The ~/.tcshrc File. The .tcshrc file contains tcsh variable settings and is executed every time a tcsh subshell is started. Aliases and history are normally set here.
(The .tcshrc File) 1 if ( $?prompt ) then 2 set prompt = "\! stardust > " 3 set history = 100 4 set savehist = 5 5 set noclobber 6 set rmstar 7 set cdpath = ( /home/jody/ellie/bin /usr/local/bin /usr/bin ) 8 set ignoreeof 9 alias m more alias status 'date;du -s' alias cd 'cd \!*;set prompt = "\! <$cwd> "' 10 endif
EXPLANATION
|
The ~/.login File. The .login file is executed one time when you first log in. It normally contains environment variables and terminal settings. It is the file where window applications are usually started. Because environment variables are inherited by processes spawned from this shell and only need to be set once, and terminal settings do not have to be reset for every process, those settings belong in the .login file.
(The .login File) 1 stty -istrip 2 stty erase ^h 3 stty kill ^u # # If possible start the windows system. # Give a user a chance to bail out # 4 if ( $TERM == "linux" ) then 5 echo "Starting X windows. Press control C \ to exit within the next 5 seconds " sleep 5 6 startx 7 endif 8 set autologout=60
EXPLANATION
|
The path variable is used by the shell to locate commands typed at the command line. The search is from left to right. The dot (.) represents the current working directory. If the command is not found in any of the directories listed in the path, or in the present working directory, the shell sends the message Command not found. to standard error. It is recommended that the path be set in the .login file.[4] The search path is set differently in the TC shell than it is in the Bash and Korn shells. Each element is separated by whitespace in the TC shell, but separated by colons in the other shells.
The TC shell internally updates the environment variable for PATH to maintain compatibility with other programs, such as the Bash, Bourne, or Korn shells, that may be started from this shell and will need to use the path variable.
# Path is set in the ~/.tcshrc file. 1 set path = (/usr/bin /bin /usr/bsd /usr/local/bin .) 2 echo $path /usr/bin /bin /usr/bsd /usr/local/bin . # The environment variable PATH will display as a colon-separated list 3 echo $PATH /usr/bin:/bin:/usr/bsd:/usr/local/bin:.
EXPLANATION
|
The rehash Command. The shell builds an internal hash table consisting of the contents of the directories listed in the search path. (If the dot is in the search path, the files in the dot directory, the current working directory, are not put in the hash table.) For efficiency, the shell uses the hash table to find commands that are typed at the command line, rather than searching the path each time. If a new command is added to one of the directories already listed in the search path, the internal hash table must be recomputed. You do this by typing the following:
rehash
The hash table is also automatically recomputed when you change your path or start another shell.
The hashstat Command. The hashstat command displays performance statistics to show the effectiveness of its search for commands from the hash table. The statistics are in terms of "hits" and "misses." If the shell finds most of its commands you used at the end of your path, it has to work harder than if they were at the front of the path, resulting in a higher number of misses than hits. In such cases, you can put the most heavily hit directory toward the front of the path to improve performance.[5] The unhash built-in command disables the use of the internal hash table.
> hashstat 1024 hash buckets of 16 bits each
The source Command. The source command is a built-in shell command, that is, part of the shell's internal code. It is used to execute a command or set of commands from a file. Normally, when a command is executed, the shell forks a child process to execute the command, so that any changes made will not affect the original shell, called the parent shell. The source command causes the program to be executed in the current shell, so that any variables set within the file will become part of the environment of the current shell. The source command is normally used to reexecute the .tcshrc, .cshrc or .login if either has been modified. For example, if the path is changed after logging in, type
> source .login or source .tcshrc
The TC shell has three prompts: the primary prompt (a > symbol), the secondary prompt (a question mark [?] followed by a tcsh command such as while, foreach, or if), and a third prompt used for the spelling correction feature. The primary prompt is the prompt that is displayed on the terminal after you have logged in. It can be reset. If you are writing scripts at the prompt that require tcsh programming constructs, for example, decision-making or looping, the secondary prompt will appear so that you can continue on to the next line. It will continue to appear after each newline until the construct has been properly terminated. The third prompt appears to confirm automatic spelling correction if spelling correction is turned on. (See "Spelling Correction".) It contains the string CORRECT > corrected command (y|n|e|a)?. The prompts can be customized by adding special formatting sequences to the prompt string. See Table 13.1.
String | What It Sets |
---|---|
%/ | The current working directory. |
%~ | The current working directory, where ~ represents the user's home directory and other users' home directories are represented by ~user. |
%c[[0]n], %.[[0]n] | The trailing component of the current working directory, or if n (a digit) is given, n trailing components. |
%C | Like %c, but without ~ substitution. |
%h, %!, ! | The current history event number. |
%M | The full hostname. |
%m | The hostname up to the first ".". |
%S (%s) | Start (stop) standout mode. |
%B (%b) | Start (stop) boldfacing mode. |
%U (%u) | Start (stop) underline mode. |
%t, %@ | The time of day in 12-hour AM/PM format. |
%T | Like %t, but in 24-hour format. |
%p | The "precise" time of day in 12-hour AM/PM format, with seconds. |
%P | Like %p, but in 24-hour format. |
^c | c is parsed as in bindkey. |
\c | c is parsed as in bindkey. |
%% | A single %. |
%n | The user name. |
%d | The weekday in Day format. |
%D | The day in dd format. |
%w | The month in Mon format. |
%W | The month in mm format. |
%y | The year in yy format. |
%Y | The year in yyyy format. |
%l | The shell's tty. |
%L | Clears from the end of the prompt to the end of the display or the end of the line. |
%$ | Expands the shell or environment variable name immediately after the $. |
%# | > (or the first character of the promptchars shell variable) for normal users, # (or the second character of promptchars) for the superuser. |
%{string%} | Includes string as a literal escape sequence. It should be used only to change terminal attributes and should not move the cursor location. This cannot be the last sequence in prompt. |
%? | The return code of the command executed just before the prompt. |
%R | In prompt2, the status of the parser. In prompt3, the corrected string. In history, the history string. |
The Primary Prompt. When running interactively, the prompt waits for you to type a command and press the Enter key. If you do not want to use the default prompt, reset it in the .tcshrc file and it will be set for this and all TC shells subsequently started. If you only want it set for this login session, set it at the shell prompt.
1 > set prompt = '[ %n@%m %c]# ' 2 [ ellie@homebound ~]# cd .. 3 [ ellie@homebound /home]# cd ..
EXPLANATION
|
The Secondary Prompt. The secondary prompt appears when you are writing online scripts at the prompt. The secondary prompt can be changed. Whenever shell programming constructs are entered, followed by a newline, the secondary prompt appears and continues to appear until the construct is properly terminated. Writing scripts correctly at the prompt takes practice. Once the command is entered and you press Enter, you cannot back up, and the tcsh history mechanism does not save commands typed at the secondary prompt.
1 > foreach pal (joe tom ann) 2 foreach? echo Hi $pal 3 foreach? end Hi joe Hi tom Hi ann 4 >
EXPLANATION
|
1 > set prompt2='%R %% ' 2 > foreach name ( joe tom ann ) 3 foreach % echo Hi $name 4 foreach % end Hi joe Hi tom Hi ann 5 >
EXPLANATION
|
After logging in, the TC shell displays its primary prompt, by default a > symbol. The shell is your command interpreter. When the shell is running interactively, it reads commands from the terminal and breaks the command line into words. A command line consists of one or more words (or tokens) separated by whitespace (blanks and/or tabs) and terminated by a newline, generated by pressing the Enter key. The first word is the command, and subsequent words are the command's options and/or arguments. The command may be a UNIX executable program such as ls or pwd, an alias, a built-in command such as cd or jobs, or a shell script. The command may contain special characters, called metacharacters, that the shell must interpret while parsing the command line. If the last character in the command line is a backslash, followed by a newline, the line can be continued to the next line.[6]
Exit Status and the printexitvalue Variable. After a command or program terminates, it returns an exit status to the parent process. The exit status is a number between 0 and 255. By convention, when a program exits, if the status returned is zero, the program was successful in its execution. When the exit status is nonzero, then it failed in some way. If the program terminated abnormally, then 0200 is added to the status. Built-in commands that fail return an exit status of 1; otherwise, they return a status of 0.
The tcsh status variable or ? variable is set to the value of the exit status of the last command that was executed. Success or failure of a program is determined by the programmer who wrote the program. By setting the tcsh variable printexitvalue, any time a program exits with a value other than zero, its status will automatically be printed.
1 > grep "ellie" /etc/passwd ellie:GgMyBsSJavd16s:501:40:E Quigley:/home/jody/ellie:/bin/tcsh 2 > echo $status or echo $? 0 3 > grep "nicky" /etc/passwd 4 > echo $status 1 5 > grep "scott" /etc/passsswd grep: /etc/passsswd: No such file or directory 6 > echo $status 2 7 > set printexitvalue > grep "XXX" /etc/passwd Exit 1 >
EXPLANATION
|
Command Grouping A command line can consist of multiple commands. Each command is separated by a semicolon and the command line is terminated with a newline.
> ls; pwd; cal 2001
EXPLANATIONThe commands are executed from left to right until the newline is reached. |
Commands may also be grouped so that all of the output is either piped to another command or redirected to a file. The shell executes commands in a subshell.
1 > ( ls ; pwd; cal 2001 ) > outputfile 2 > pwd; ( cd / ; pwd ) ; pwd /home/jody/ellie / /home/jody/ellie
EXPLANATION
|
Conditional Execution of Commands. With conditional execution, two command strings are separated by two special metacharacters: two ampersands (&&), or double vertical lines (||). The command on the right of either of these metacharacters will or will not be executed based on the exit condition of the command on the left.
> grep '^tom:' /etc/passwd && mail tom < letter
EXPLANATIONIf the first command is successful (has a zero exit status), the second command after the && is executed. If the grep command successfully finds tom in the passwd file, the command on the right will be executed: The mail program will send tom the contents of the letter file. |
> grep '^tom:' /etc/passwd || echo "tom is not a user here."
EXPLANATIONIf the first command fails (has a nonzero exit status), the second command after the || is executed. If the grep command does not find tom in the passwd file, the command on the right will be executed: The echo program will print tom is not a user here to the screen. |
Commands in the Background. Normally, when you execute a command, it runs in the foreground, and the prompt does not reappear until the command has completed execution. It is not always convenient to wait for the command to complete. When you place an ampersand at the end of the command line, the shell prompt will return immediately so that you do not have to wait for the last command to complete before starting another one. The command running in the background is called a background job and its output will be sent to the screen as it processes. It can be confusing if two commands are sending output to the screen concurrently. To avoid confusion, you can send the output of the job running in the background to a file or pipe it to another device such as a printer. It is often handy to start a new shell window in the background. Then you will have access to both the window from which you started and the new shell window.
1 > man tcsh | lpr & 2 [1] 4664 3 >
EXPLANATION
|
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. In addition to 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 whitespace 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 13.2.) The history built-in command displays the history list. It supports a number of arguments to control how the history is displayed.
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.
(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
EXPLANATIONThe 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 13.1.) The default format string for history is: %h\t%T\t%R\n.
1 set history=1000 2 set history= ( 1000 '%B%h %R\n' ) 3 history 136 history 137 set history = ( 1000 '%B%h %R\n' ) 138 history 139 ls 140 pwd 141 cal 141 pwd 142 cd
EXPLANATION
|
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 timestamp, and the most recent events saved.
1 set savehist 2 set savehist = 1000 3 set savehist = 1000 merge
EXPLANATION
|
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.
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 > 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
|
> 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
EXPLANATIONThe history list is displayed in reverse order. |
> history 5 # Print the last 5 events on the history list 7 echo $USER 8 cd 9 set 10 history -n 11 history 5
EXPLANATIONThe 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.
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 Table 13.5 and Table 13.6). The arrow keys behave the same way for both the vi and emacs key bindings. (See Table 13.3.)
Up arrow moves up the history list. | |
Down arrow moves down the history list. | |
Right arrow moves cursor to right on history command. | |
Left arrow moves cursor to left on history command. |
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 13.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\1 shell variable.
1 > date Mon Feb 8 12:27:35 PST 2001 2 > !! date Mon Aug 10 12:28:25 PST 2001 3 > !3 date Mon Aug 10 12:29:26 PST 2001 4 > !d date Mon Aug 10 12:30:09 PST 2001 5 > dare dare: Command not found. 6 > ^r^t date Mon Apr 10 16:15:25 PDT 2001 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 > 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
|
Event Designators | Meaning |
---|---|
! | Indicates the start of history substitution. |
!! | Reexecutes the previous command. |
!N | Reexecutes the Nth command from the history list. |
!-N | Reexecutes the Nth 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 Nth command in history list and executes. |
!N:s/old/new/ | In previous Nth command, substitutes the first occurrence of old string with new string. |
!N:gs/old/new/ | In previous Nth 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 Nth 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. |
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 key bindings 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" on page 858.
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 13.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).
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 13.6.
Command | Function |
---|---|
Ctrl-P | Move up history file. |
Ctrl-N | Move down 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 key bindings including key bindings for emacs and vi. The key bindings 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.
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 13.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 13.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 or vi editor commands, but also to UNIX commands and strings.
Characters | Meaning |
---|---|
^C | Control-C. |
^[ | Esc. |
^? | Del. |
\a | Control-G (bell). |
\b | Control-H (backspace). |
\e | Esc (escape). |
\f | Formfeed. |
\n | Newline. |
\r | Return. |
\t | Tab. |
\v | Control-K (vertical tab). |
\nnn | ASCII octal number. |
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 > 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!\n' > 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
|
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 command. |
bindkey -s key string | Bind key to string. |
bindkey -r key | Remove key binding. |
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 13.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 pressed.
1 > ls file1 file2 foo foobarckle fumble 2 > lsfu[tab] # eExpands 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 2001 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
|
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.
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
|
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.
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
|
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 is 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 cd command 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 13.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 13.31 for p-type completions.
# 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
|
Word | Type |
---|---|
a | Alias. |
b | Editor key-binding commands. |
c | Commands (built-in or external). |
C | External commands that begin with the supplied path prefix. |
d | Directory. |
D | Directories that begin with the supplied path prefix. |
e | Environment variables. |
f | Filenames (not directory). |
F | Filenames that 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.
# 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
|
An n-type completion matches the first word and completes the second one.
# 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
|
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 dirs built-in command, 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 nth 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" on page 905.)
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.
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 nth 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. |
1 > pwd /home/ellie > pushd .. /home ~ > pwd /home 2 > pushd # Swap the two top directories on the stack ~ /home > pwd /home/ellie
EXPLANATION
|
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]
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.
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 2001 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
|
Argument | What It Does |
---|---|
cmd | Spell-corrects commands. |
complete | Completes commands. |
all | Spell-corrects entire command line. |
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\1, cwdcmd\1, periodic\1, and precomd\1. These aliases are listed and defined in "Special Aliases".
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.
> 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 mroe 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)
EXPLANATIONThe 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.
FORMATalias alias aliasname command alias aliasname 'command command(s)' unalias aliasname |
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
|
[a] If using /bin/csh as your shell, replace %/ with $cwd when setting the prompt.
Deleting Aliases. The unalias command is used to delete an alias. To temporarily turn off an alias, precede the alias name by a backslash.
1 > unalias mroe 2 > \cd ..
EXPLANATION
|
Alias Loop. An alias loop occurs when an alias definition references another alias that references back to the original alias.
1 > alias m more 2 > alias mroe m 3 > alias m mroe # Causes a loop 4 > m datafile Alias loop.
EXPLANATION
|
Job control is a powerful feature of the TC shell that allows you to run programs, called jobs, in the background or foreground. Normally, a command typed at the command line is running in the foreground and will continue until it has finished. If you have a windowing program, job control may not be necessary because you can simply open another window to start a new task. On the other hand, with a single terminal, job control is a very useful feature. For a list of job commands, see Table 13.12.
Command | Meaning |
---|---|
jobs | Lists all the jobs running. |
^Z (Ctrl-Z) | Stops (suspends) the job; the prompt appears on the screen. |
bg | Starts running the stopped job in the background. |
fg | Brings a background job to the foreground. |
kill | Sends the kill signal to a specified job. |
Argument to Jobs Command | Represents |
---|---|
%n | Job number n. |
%string | Job name starting with string. |
%?string | Job name containing string. |
%% | Current job. |
%+ | Current job. |
%- | Previous job, before current job. |
The Ampersand. If a command takes a long time to complete, you can append the command with an ampersand and the job will execute in the background. The tcsh prompt returns immediately and now you can type another command. Now the two commands are running concurrently, one in the background and one in the foreground. They both send their standard output to the screen. If you place a job in the background, it is a good idea to redirect its output either to a file or pipe it to a device such as a printer.
1 > find . -name core -exec rm {} \; & 2 [1] 543 3 >
EXPLANATION
|
[a] The find syntax requires a semicolon at the end of an exec statement. The semicolon is preceded by a backslash to prevent the shell from interpreting it.
The Suspend Key Sequence. To suspend a program, the suspend key sequence, ^Z, is issued. The job is now suspended (stopped), the shell prompt is displayed, and the program will not resume until the fg or bg commands are issued. (When using the vi editor, the ZZ command writes and saves a file. Do not confuse this with ^Z, which would suspend the vi session.) If you try to log out when a job is suspended, the message There are suspended jobs appears on the screen.
The jobs Command and the listjobs Variable. The tcsh built-in command jobs displays the programs that are currently active and either running or suspended in the background. Running means the job is executing in the background. When a job is suspended, it is stopped; it is not in execution. In both cases, the terminal is free to accept other commands. If you attempt to exit the shell while jobs are stopped, the warning, There are suspended jobs will appear on the screen. When you attempt to exit immediately a second time, the shell will go ahead and terminate the suspended jobs. You set the tcsh built-in listjobs variable if you want to automatically print a message when you suspend a job.
(The Command Line) 1 > jobs 2 [1] + Suspended vi filex [2] - Running sleep 25 3 > jobs -l [1] + 355 Suspended vi filex [2] - 356 Running sleep 25 4 [2] Done sleep 25 5 > set listjobs = long > sleep 1000 Press Control-Z to suspend job [1] + 3337 Suspended sleep 1000 > 6 > set notify
EXPLANATION
|
The fg command brings a background job into the foreground. The bg command starts a suspended job running in the background. A percent sign and the number of a job can be used as arguments to fg and bg if you want to select a particular job for job control.
1 > jobs 2 [1] + Suspended vi filex [2] - Running cc prog.c -o prog 3 > fg %1 vi filex (vi session starts) 4 > kill %2 [2] Terminated c prog.c -o prog 5 > sleep 15 (Press ^z) Suspended 6 > bg [1] sleep 15 & [1] Done sleep 15
EXPLANATION
|
[a] Programs such as grep, sed, and awk have a set of metacharacters, called regular expression metacharacters, for pattern matching. These should not be confused with shell metacharacters.
The sched built-in command allows you to create a list of jobs that will be scheduled to run at some specific time. The sched command, without arguments, displays a numbered list of all the scheduled events. It sets times in the form hh:mm (hour:minute) where hour can be in military or 12-hour AM/PM format. Time can also be specified as a relative time with a + sign; i.e., relative to the current time, and with a - sign, the event is removed from the list.[9]
FORMATsched sched [+]hh:mm command sched -n |
1 > sched 14:30 echo '^G Time to start your lecture!' 2 > sched 5PM echo Time to go home. 3 > sched +1:30 /home/ellie/scripts/logfile.sc 4 > sched 1 17:47 /home/scripts/logfile.sc 2 5PM echo Time to go home. 3 14:30 echo '^G Time to start your lecture!' 5 > sched -2 > sched 1 17:47 /home/scripts/logfile.sc 2 14:30 echo '^G Time to start your lecture!'
EXPLANATION
|
[a] To get the ^G into the echo statement, type Ctrl-M followed by Ctrl-V, followed by Ctrl-G.
Metacharacters are special characters that are used to represent something other than themselves. As a rule of thumb, characters that are neither letters nor numbers may be metacharacters. The shell has its own set of metacharacters, often called shell wildcards. Shell metacharacters can be used to group commands together, to abbreviate filenames and pathnames, to redirect and pipe input/output, to place commands in the background, and so forth. Table 13.13 presents a partial list of shell metacharacters.
Metacharacter | Purpose | Example | Meaning |
---|---|---|---|
$ | Variable substitution | set name=Tom echo $name Tom | Sets the variable name to Tom; displays the value stored there. |
! | History substitution | !3 | Reexecutes the third event from the history list. |
* | Filename substitution | rm * | Removes all files. |
? | Filename substitution | ls ?? | Lists all two-character files. |
[ ] | Filename substitution | cat f[123] | Displays contents of f1, f2, f3. |
; | Command separator | ls;date;pwd | Each command is executed in turn. |
& | Background processing | lp mbox& | Printing is done in the background. Prompt returns immediately. |
> | Redirection of output | ls > file | Redirects standard output to file. |
< | Redirection of input | ls < file | Redirects standard input from file. |
>& | Redirection of output and error | ls >& file | Redirects both output and errors to file. |
>! | If noclobber is set, override it | ls >! file | If file exists, truncate and overwrite it, even if noclobber is set. |
>>! | If noclobber is set, override it | ls >>! file | If file does not exist, create it, even if noclobber is set. |
( ) | Groups commands to be executed in a subshell | (ls ; pwd) >tmp | Executes commands and sends output to tmp file. |
{ } | Groups commands to be executed in this shell | { cd /; echo $cwd } | Changes to root directory and displays current working directory. |
When evaluating the command line, the shell uses metacharacters to abbreviate filenames or pathnames that match a certain set of characters. The filename substitution metacharacters listed in Table 13.14 are expanded into an alphabetically listed set of filenames. The process of expanding a metacharacter into filenames is also called globbing. Unlike the other shells, when the C shell cannot substitute a filename for the metacharacter it is supposed to represent, the shell reports No match.
Metacharacter | Meaning |
---|---|
* | Matches zero or more characters. |
? | Matches exactly one character. |
[abc] | Matches one character in the set a, b, or c. |
[a z] | Matches one character in the range a to z. |
[^abc] | Matches any character that is not a, b, or c. |
{a, ile, ax} | Matches for a character or set of characters. |
~ | Substitutes the user's home directory for tilde. |
\ | Escapes or disables the metacharacter. |
Expanding the Metacharacters. The shell performs filename substitution by evaluating its metacharacters and replacing them with the appropriate letters or digits in a filename.
The Asterisk. The asterisk matches zero or more characters in a filename.
1 > ls a.c b.c abc ab3 file1 file2 file3 file4 file5 2 > echo * a.c b.c abc ab3 file1 file2 file3 file4 file5 3 > ls *.c a.c b.c 4 > ls ^*.c abc ab3 file1 file2 file3 file4 file5 5 > rm z*p No match.
EXPLANATION
|
The Question Mark. The question mark matches exactly one character in a filename.
1 > ls a.c b.c abc ab3 file1 file2 file3 file4 file5 2 > ls ??? abc ab3 3 > echo How are you? No match. 4 > echo How are you\? How are you?
EXPLANATION
|
The Square Brackets. The square brackets ([])match a filename for one character from a set or range of characters.
1 > ls a.c b.c abc ab3 file1 file2 file3 file4 file5 file10 file11 file12 2 > ls file[123] file1 file2 file3 3 > ls file[^123] file4 file5 4 > ls [A-Za-z][a-z][1-5] ab3 5 > ls file1[0-2] file10 file11 file12
EXPLANATION
|
The Curly Braces. The curly braces ({})match for a character or string of characters in a filename that may or may not already exist.
1 > ls a.c b.c abc ab3 ab4 ab5 file1 file2 file3 file4 file5 foo faa fumble 2 > ls f{oo,aa,umble} foo faa fumble 3 > ls a{.c,c,b[3-5]} a.c ab3 ab4 ab5 4 > mkdir prog{1,2,3} 5 > echo tweedle{dee,dum}, {l,cl,m}ove{r} tweedledee tweedledum, lover clover mover
EXPLANATION
|
Escaping Metacharacters and nonomatch. The backslash is used to escape the special meaning of a single character. The escaped character will represent itself.
1 > got milk? got: No match. 2 > got milk\? got: Command not found. 3 > set nonomatch > got milk? got: Command not found.
EXPLANATION
|
Tilde Expansion. The tilde character (~) by itself expands to the full pathname of the user's home directory. When the tilde is prepended to a username, it expands to the full pathname of that user's home directory. When prepended to a path, it expands to the home directory and the rest of the pathname.
1 > echo ~ /home/jody/ellie 2 > cd ~/desktop/perlstuff > pwd /home/jody/ellie/desktop/perlstuff 3 > cd ~joe > pwd /home/bambi/joe
EXPLANATION
|
Turning Off Metacharacters with noglob. If the noglob variable is set, filename substitution is turned off, meaning that all metacharacters represent themselves; they are not used as wildcards. This can be useful when searching for patterns in programs like grep, sed, or awk, which may contain metacharacters that the shell may try to expand.
1 > set noglob 2 > echo * ?? [] ~ * ?? [] ~
EXPLANATION
|
Normally, standard output (stdout) from a command goes to the screen, standard input (stdin) comes from the keyboard, and error messages (stderr) go to the screen. The shell allows you to use the special redirection metacharacters to redirect the input/output to or from a file. The redirection operators (<, >, >>, >&) are followed by a filename. This file is opened by the shell before the command on the left-hand side is executed.
Pipes, represented by a vertical bar (|) symbol, allow the output of one command to be sent to the input of another command. The command on the left-hand side of the pipe is called the writer because it writes to the pipe. The command on the right-hand side of the pipe is the reader because it reads from the pipe. See Table 13.15 for a list of redirection and pipe metacharacters.
Metacharacter | Meaning |
---|---|
command < file | Redirects input from file to command. |
command > file | Redirects output from command to file. |
command >& file | Redirects output and errors to file. |
command >> file | Redirects output of command and appends it to file. |
command >>& file | Redirects and appends output and errors of command to file. |
command << WORD | Redirects input from first WORD to terminating WORD to command. |
<input> | User input goes here. It will be treated as a doubly quoted string of text. |
WORD | WORD marks the termination of input to command. |
command | command | Pipes output of first command to input of second command. |
command |& command | Pipes output and errors of first command to input of second command. |
command >! file | If the noclobber variable is set, overrides its effects for this command and either open or overwrite file. |
command >>! file | Overrides noclobber variable; if file does not exist, it is created and output from command is appended to it. |
command >>&! file | Overrides noclobber variable; if file does not exist, it is created and both output and errors are appended to it. |
Instead of the input coming from the terminal keyboard, it can be redirected from a file. The shell will open the file on the right-hand side of the < symbol and the program on the left will read from the file. If the file does not exist, the error No such file or directory will be reported by the shell.
FORMATcommand < file |
mail bob < memo
EXPLANATIONThe file memo is opened by the shell, and the input is redirected to the mail program. Simply, the user bob is sent a file called memo by the mail program. |
The here document is another way to redirect input to a command in the form of a quoted block of text. It is used in shell scripts for creating menus and processing input from other programs. Normally, programs that accept input from the keyboard are terminated with Control-D (^D). The here document provides an alternate way of sending input to a program and terminating the input without typing ^D. The << symbol is followed by a user-defined word, often called a terminator. Input will be directed to the command on the left-hand side of the << symbol until the user-defined terminator is reached. The final terminator is on a line by itself, and cannot be surrounded by any spaces. Variable and command substitution are performed within the here document. Normally, here documents are used in shell scripts to create menus and provide input to commands such as mail, bc, ex, ftp, etc.
FORMATcommand << MARK ... input ... MARK |
(Without the here document) (The Command Line) 1 > cat 2 Hello There. How are you? I'm tired of this. 3 ^d (The Output) 4 Hello There. How are you? I'm tired of this.
EXPLANATION
|
(With the here document) (The Command Line) 1 > cat << DONE 2 ? Hello There. ? How are you? ? I'm tired of this. 3 ? DONE 4 Hello There. <----The output from the here document How are you? I'm tired of this.
EXPLANATION
|
(The Command Line) 1 > set name = steve 2 > mail $name << EOF 3 ? Hello there, $name 4 ? The hour is now 'date +%H' 5 ? EOF 6 >
EXPLANATION
|
By default, the standard output of a command or commands goes to the terminal screen. To redirect standard output from the screen to a file, use the > symbol. The command is on the left-hand side of the > symbol, and a filename is on the right-hand side. The shell will open the file on the right-hand side of the > symbol. If the file does not exist, the shell will create it; if it does exist, the shell will open the file and truncate it. Often files are inadvertently removed when using redirection. (A special tcsh variable, called noclobber, can be set to prevent redirection from clobbering an existing file. See Table 13.16.)
FORMATcommand > file |
cat file1 file2 > file3
EXPLANATIONThe contents of file1 and file2 are concatenated and the output is sent to file3. Remember that the shell opens file3 before it attempts to execute the cat command. If file3 already exists and contains data, the data will be lost. If file3 does not exist, it will be created. |
Appending Output to an Existing File. To append output to an existing file, use the >> symbol. If the file on the right-hand side of the >> symbol does not exist, it is created; if it does exist, the file is opened and output is appended to the end of the file.
FORMATcommand >> file |
date >> outfile
EXPLANATIONThe standard output of the date command is redirected and appended to outfile. |
Redirecting Output and Error. The >& symbol is used to redirect both standard output and standard error to a file. Normally, a command is either successful and sends its output to stdout, or fails and sends its error messages to stderr. Some recursive programs, such as find and du, send both standard output and errors to the screen as they move through the directory tree. When you use the >& symbol, both standard output and standard error can be saved in a file and examined. The TC shell does not provide a symbol for redirection of only standard error, but it is possible to get just the standard error by executing the command in a subshell. See Figure 13.3.
1 > date Tue Aug 3 10:31:56 PDT 2001 2 > date >& outfile 3 > cat outfile Tue Aug 3 10:31:56 PDT 2001
EXPLANATION
|
1 > cp file1 file2 2 > cp file1 cp: missing destination file Try 'cp --help' for more information 3 > cp file1 >& errorfile 4 > cat errorfile cp: missing destination file Try 'cp --help' for more information
EXPLANATION
|
Separating Output and Errors. Standard output and standard error can be separated by enclosing the command in parentheses. When a command is enclosed in parentheses, the TC shell starts up a subshell, handles redirection from within the subshell, and then executes the command. By using the technique shown in Example 13.59, you can separate the standard output from the errors.
(The Command Line) 1 > find . -name '*.c' >& outputfile 2 > (find . -name '*.c' > goodstuff) >& badstuff
EXPLANATION
|
The noclobber Variable. The special TC shell built-in variable noclobber, when set, protects you from clobbering files with redirection. See Table 13.16.
noclobber Is Not Set | File Exists | File Does Not Exist |
---|---|---|
command > file | file is overwritten. | file is created. |
command >> file | file is appended to. | file is created. |
noclobber Is Set | ||
command > file | Error message. | file is created. |
command >> file | File is appended to. | Error message. |
Overwriting noclobber | ||
command >! file | If the noclobber variable is set, override its effects for this command and either open or truncate file, redirecting output of command to file. | |
command >>! file | Override noclobber variable; if file does not exist, it is created and output from command is appended to it. |
1 > cat filex abc 123 2 > date > filex 3 > cat filex Tue Mar 18 11:51:04 PST 2001 4 > set noclobber 5 > date > filex filex: File exists. 6 > ls >! filex # Override noclobber for this command only > cat filex abc ab1 dir filex plan.c 7 > ls > filex filex: File exists. 8 > date >> XXX XXX: No such file or directory. 9 > date >>! XXX # Override noclobber for this command only 10 > unset noclobber # Turn off noclobber permanently
EXPLANATION
|
Tcsh variables hold only strings or a set of strings. Some variables are built into the shell and can be set either by turning them on or off, such as the noclobber or filec variable. Others are assigned a string value, such as the path variable. You can create your own variables and assign them to strings or the output of commands. Variable names are case-sensitive and may contain up to 20 characters consisting of numbers, letters, and the underscore.
There are two types of variables: local and environment. The scope of a variable is its visibility. A local variable is visible to the shell where it is defined. The scope of environment variables is often called global. Their scope is for this shell and all processes spawned (started) from this shell. If a local variable is created with set -r, it will be read-only, meaning that it cannot be changed or unset.
The dollar sign ($) is a special metacharacter that, when preceding a variable name, tells the shell to extract the value of that variable. The echo command, when given the variable as an argument, will display the value of the variable after the shell has processed the command line and performed variable substitution.
The special notation $?, when prepended to the variable name, lets you know whether the variable has been set. If a one is returned, it means true, the variable has been set. If a zero is returned, it means false, the variable has not been set.
1 > set autologout 2 > set history = 50 3 > set name = George 4 > set machine = 'uname -n' 5 > echo $?machine 1 6 echo $?blah 0
EXPLANATION
|
The echo Command. The built-in echo command prints its arguments to standard output. The echo allows the use of numerous escape sequences, which are interpreted and displayed as tabs, newlines, form feed, etc. Table 13.17 lists the echo options and escape sequences.
The TC shell uses the style of both BSD and SVR4, but allows you to modify the behavior of the echo command by using the built-in echo_style variable; e.g., set echo_style=bsd. See Table 13.18. See the manual page for echo.
Option | Meaning |
---|---|
-n | Suppresses newline at the end of a line of output. |
Escape Sequence | |
\a | Alert (bell). |
\b | Backspace. |
\c | Print the line without a newline. |
\f | Form feed. |
\n | Newline. |
\r | Return. |
\t | Tab. |
\v | Vertical tab. |
\\ | Backslash. |
\nnn | The character whose ASCII code is nnn (octal). |
bsd | If the first argument is -n, the newline is suppressed. |
sysv | Expands escape sequences in echo strings. |
both | Both -n and escape sequences are in effect (the default). |
none | Recognizes neither sysv or bsd. |
1 > echo The username is $LOGNAME. The username is ellie. 2 > echo "\t\tHello there\c" Hello there> 3 > echo -n "Hello there" Hello there$ 4 > set echo_style=none 5 > echo "\t\tHello there\c" -n \t\tHello there\c
EXPLANATION
|
The printf Command. The GNU version of printf can be used to format printed output. It prints the formatted string in the same way as the C printf function. The format consists of a string that may contain formatting instructions to describe how the printed output will look. The formatting instructions are designated with a % followed by specifiers (diouxXfeEgGcs), where %f would represent a floating point number and %d would represent a whole (decimal) number.
To see a complete listing of printf specifiers and how to use them, type at the command line prompt: printf - -help. To see what version of printf you are using, type printf - -version. If using bash 2.x, the built-in printf command uses the same format as the executable version in /usr/bin.
FORMATprintf format [argument...] |
printf "%10.2f%5d\n" 10.5 25
Format Specifier | Value |
---|---|
\" | Double quote. |
\0NNN | An octal character in which NNN represents 0 to 3 digits. |
\\ | Backslash. |
\a | Alert or beep. |
\b | Backspace. |
\c | Produce no further output. |
\f | Form feed. |
\n | Newline. |
\r | Carriage return. |
\t | Horizontal tab. |
\v | Vertical tab. |
\xNNN | Hexadecimal character in which NNN is 1 to 3 digits. |
%% | Single %. |
%b | ARGUMENT as a string with \ escapes interpreted. |
1 > printf --version printf (GNU sh-utils) 1.16 2 > printf "The number is %.2f\n" 100 The number is 100.00 3 > printf "%-20s%-15s%10.2f\n" "Jody" "Savage" 28 Jody Savage 28.00 4 > printf "|%-20s|%-15s|%10.2f|\n" "Jody" "Savage" 28 |Jody |Savage | 28.00| 5 > printf "%s's average was %.1f%%.\n" "Jody" $(( (80+70+90)/3 )) Jody's average was 80.0%.
EXPLANATION
|
Curly Braces and Variables. Curly braces insulate a variable from any characters that may follow it. They can be used to concatenate a string to the end of the variable.
1 > set var = net > echo $var net 2 > echo $varwork varwork: Undefined variable. 3 > echo ${var}work network
EXPLANATION
|
Local variables are known only in the shell where they were created. If a local variable is set in the .tcshrc file, the variable will be reset every time a new TC shell is started. By convention, local variables are named with lowercase letters.
Setting Local Variables. If the string being assigned contains more than one word, it must be quoted; otherwise, only the first word will be assigned to the variable. It does not matter if there are spaces around the equal sign, but if there is a space on one side of the equal sign, there must be one on the other side.
1 > set round = world 2 > set name = "Santa Claus" 3 > echo $round world 4 > echo $name Santa Claus 5 > tcsh # Start a subshell 6 > echo $name name: Undefined variable.
EXPLANATION
|
Read-Only Variables. Read-only variables are local variables that, once set, cannot be changed or unset or an error message will result. Environment variables cannot be made read-only.
1 > set -r name = Tommy 2 > unset name unset: $name is read-only. 3 > set name = Danny set: $name is read-only
The set Command. The set command prints all local variables set for this shell.
(The Command Line) > set addsuffix argv () cwd /home/jody/meta dirstack /home/ellie/meta echo_style both edit gid 501 group ellie history 500 home /home/ellie i /etc/profile.d/mc.csh owd /home/ellie noclobber path (/usr/sbin /sbin /usr/local/bin /bin /usr/bin /usr/X11R6/bin ) prompt [%n@%m %c]# prompt2 %R? prompt3 CORRECT>%R (y|n|e|a)? savedirs shell /bin/tcsh shlvl 2 status 0 tcsh 6.07.09 term xterm user ellie version tcsh 6.09.09 (Astron) 1998-08-16 (sparc-sun-solaris) options 8b,nls,dl,al,rh,color
EXPLANATIONAll of the local variables set for this shell are printed. Many of these variables, such as history, dirstack, and noclobber, are set in the .tcshrc file. Others, such as argv, cwd, shell, term, user, version, and status variables are preset, built-in variables. |
Built-In Local Variables. The shell has a number of predefined variables with their own definitions. Some of the variables are either on or off. For example, if you set noclobber, the variable is on and effective, and when you unset noclobber, it is turned off. Some variables require a definition when set. Built-in variables are usually set in the .tcshrc file if they are to be effective for all interactive TC shells and tcsh scripts. Some of the built-in variables already discussed include noclobber, cdpath, history, rmstar, and noglob. For a complete list, see Table 13.24.
Environment variables are often called global variables. They are defined in the shell where they were created and inherited by all shells spawned from that shell. Although environment variables are inherited by subshells, those defined in subshells are not passed back to parent shells. Inheritance is from parent to child, not the other way around (like real life). By convention, environment variables are named with capital letters.
(The Command Line) 1 > setenv TERM wyse 2 > setenv PERSON "Joe Jr." 3 > echo $TERM wyse 4 > echo $PERSON Joe Jr. 5 > echo $$ # $$ evaluates to the PID of the current shell 206 6 > tcsh # Start a subshell 7 > echo $$ 211 8 > echo $PERSON Joe Jr. 9 > setenv PERSON "Nelly Nerd" 10 > echo $PERSON Nelly Nerd 11 > exit # Exit the subshell 12 > echo $$ 206 13 > echo $PERSON # Back in parent shell Joe Jr.
EXPLANATION
|
Displaying Environment Variables. The printenv (BSD) and env (SVR4) commands print all the environment variables set for this shell and its subshells. The setenv command prints variables and their values on both the UCB and SVR4 versions of TC shell.
> env or printenv or setenv USERNAME=root COLORTERM=rxvt-xpm HISTSIZE=1000 HOSTNAME=homebound LOGNAME=ellie HISTFILESIZE=1000 MAIL=/var/spool/mail/ellie MACHTYPE=i386 COLORFGBG=0;default;15 TERM=xterm HOSTTYPE=i386-unix PATH=/usr/sbin:/sbin:/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/ ellie/bin;/root/bash-2.03/:/usr/X11R6/bin:/home/ellie/bin;/root/bash- 2.03/:/usr/X11R6/bin HOME=/root SHELL=/bin/bash PS1=[\u@\h \W]\$ USER=ellie VENDOR=intel GROUP=ellie HOSTDISPLAY=homebound:0.0 DISPLAY=:0.0 HOST=homebound OSTYPE=unix WINDOWID=37748738 PWD=/home/ellie SHLVL=6 _=/usr/bin/env
EXPLANATIONThe environment variables are set for this session and all processes that are started from this shell are displayed by using either one of the built-in commands: env or printenv. Many applications require the setting of environment variables. For example, the mail command has a MAIL variable set to the location of the user's mail spooler and the xterm program has a DISPLAY variable that determines which bit map display terminal to use. When any of these programs are executed, the values in their respective variables are passed on to them. |
In the TC shell, an array is simply a list of words, separated by spaces or tabs, and enclosed in parentheses. The elements of the array are numbered by subscripts starting at one. If there is not an array element for a subscript, the message Subscript out of range is displayed. Command substitution will also create an array. If the $# notation precedes an array name, the number of elements in the array is displayed.
1 > set fruit = ( apples pears peaches plums ) 2 > echo $fruit apples pears peaches plums 3 > echo $fruit[1] # Subscripts start at 1 apples 4 > echo $fruit[2 4] # Prints the 2nd, 3rd, and 4th elements pears peaches plums 5 > echo $fruit[6] Subscript out of range. 6 > echo $fruit[*] # Prints all elements of the array apples pears peaches plums 7 > echo $#fruit # Prints the number of elements 4 8 > echo $%fruit # Prints the number of characters in the list 23 9 > echo $fruit[$#fruit] # Prints the last element plums 10 > set fruit[2] = bananas # Reassigns the second element > echo $fruit apples bananas peaches plums 11 > set path = ( ~ /usr/bin /usr /usr/local/bin . ) > echo $path /home/jody/ellie /usr/bin /usr /usr/local/bin . 12 > echo $path[1] /home/jody/ellie
EXPLANATION
|
The shift Command and Arrays. If the built-in shift command takes an array name as its argument, it shifts off (to the left) the first element of the array. The length of the array is decreased by one. Without an argument, the shift command shifts off the first element of the built-in argv array.
Special Modifier | Example | What It Means |
---|---|---|
$? | $?var | Returns 1 if var is set; 0 if not. |
$# | $#var | Returns the number of words in var. |
$% | $%var | Returns the number of characters in var. |
1 > set names = ( Mark Tom Liz Dan Jody ) 2 > echo $names Mark Tom Liz Dan Jody 3 > echo $names[1] Mark 4 > shift names 5 > echo $names Tom Liz Dan Jody 6 > echo $names[1] Tom 7 > set days = ( Monday Tuesday ) 8 > shift days 9 > echo $days Tuesday 10 > shift days 11 > echo $days 12 > shift days shift: no more words.
EXPLANATION
|
Creating an Array from a String. You may want to create a wordlist out of a quoted string. This is accomplished by placing the string variable within a set of parentheses.
1 > set name = "Thomas Ben Savage" > echo $name[1] Thomas Ben Savage 2 > echo $name[2] Subscript out of range. 3 > set name = ( $name ) 4 > echo $name[1] $name[2] $name[3] Thomas Ben Savage
EXPLANATION
|
Built into the TC shell are several variables consisting of one character. The $ preceding the character allows variable interpretation. See Table 13.21.
Variable | Example | Meaning |
---|---|---|
$?var | echo $?name | Returns 1 if variable has been set, 0 if not. |
$#var | echo $#fruit | Prints the number of elements in an array. |
$%var | echo $%name | Prints number of characters in a variable or array. |
$$ | echo $$ | Prints the PID of the current shell. |
$< | set name = $< | Accepts a line of input from user up to newline. |
$? | echo $? | Same as $status. Contains the exit status of the last command. |
$! | kill $! | Contains the process ID number of the last job put in the background. |
1 > set num > echo $?num 1 2 > echo $path /home/jody/ellie /usr /bin /usr/local/bin > echo $#path 3 3 > echo $$ 245 > tcsh # Start a subshell > echo $$ 248 4 > set name = $< Christy Campbell > echo $name Christy 5 > set name = "$<" Christy Campbell > echo $name Christy Campbell
EXPLANATION
|
If a pathname is assigned to a variable, it is possible to manipulate the pathname variable by appending special TC shell extensions to it. The pathname is divided into four parts: head, tail, root, and extension. See Table 13.22 for examples of pathname modifiers and what they do.
set pn = /home/ellie/prog/check.c | |||
---|---|---|---|
Modifier | Meaning | Example | Result |
:r | root | echo $pn:r | /home/ellie/prog/check |
:h | head | echo $pn:h | /home/ellie/prog |
:t | tail | echo $pn:t | check.c |
:e | extension | echo $pn:e | c |
:g | global | echo $p:gt | (See Example 13.75) |
1 > set pathvar = /home/danny/program.c 2 > echo $pathvar:r /home/danny/program 3 > echo $pathvar:h /home/danny 4 > echo $pathvar:t program.c 5 > echo $pathvar:e c 6 > set pathvar = ( /home/* ) echo $pathvar /home/jody /home/local /home/lost+found /home/perl /home/tmp 7 > echo $pathvar:gt jody local lost+found perl tmp
EXPLANATION
|
A special history modifier can be used to change the case of letters in a variable.
Modifier | Effect |
---|---|
:u | Uppercase the first lowercase letter in a word. |
:l | Lowercase the first uppercase letter in a word. |
:g | Apply a modifier once to each word. |
:a | Apply a modifier as many times as possible to a single word. |
1 > set name = nicky > echo $name:u Nicky 2 > set name = ( nicky jake ) > echo $name:gu Nicky Jake 3 > echo $name:agu NICKY JAKE 4 > set name = ( TOMMY DANNY ) > echo $name:agl tommy danny 5 > set name = "$name:agu > echo $name TOMMY DANNY
EXPLANATION
|
A string or variable can be assigned the output of a UNIX command by placing the command in backquotes. This is called command substitution. (On the keyboard, the backquotes are normally below the tilde character.) If the output of a command is assigned to a variable, it is stored as a wordlist or array. (See "Wordlists and Command Substitution" on page 919.)
1 > echo The name of my machine is 'uname -n'. The name of my machine is stardust. 2 > echo The present working directory is 'pwd'. The present working directory is /home/stardust/john. 3 > set d = 'date' > echo $d Tue Mar 28 14:24:21 PDT 2001
EXPLANATION
|
Wordlists and Command Substitution. When a command is enclosed in backquotes and assigned to a variable, the resulting value is an array (wordlist). Each element of the array can be accessed by appending a subscript to the array name. The subscripts start at one. If a subscript that is greater than the number of words in the array is used, the TC shell prints Subscript out of range. If the output of a command consists of more than one line, the newlines are stripped from each line and replaced with a single space.
After an array is created, the built-in shift command can be used to remove words starting at word number one. Once a word is shifted off, it cannot be retrieved.
1 > set d = 'date' > echo $d Tue Mar 28 14:04:49 PST 2001 2 > echo $d[1 3] Tue Mar 28 3 > echo $d[6] 2001 4 > echo $d[7] Subscript out of range. 5 > echo "The calendar for the month of March is 'cal 3 2000'" The calendar for month of March is March 2001 S M Tu W Th F S 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
EXPLANATION
|
1 > set machine = 'rusers | awk '/tom/{print $1}'' 2 > echo $machine dumbo bambi dolphin 3 > echo $#machine 3 4 > echo $machine[$#machine] dolphin 5 > echo $machine dumbo bambi dolphin 6 > shift $machine > echo $machine bambi dolphin 7 > echo $machine[1] bambi 8 > echo $#machine 2
EXPLANATION
|
The TC shell has a whole set of metacharacters that have some special meaning. In fact, almost any character on your keyboard that is not a letter or a number has some special meaning for the shell. Here is a partial list:
* ? [ ] $ ~ ! ^ & { } ( ) > < | ; : %
The backslash and quotes are used to escape the interpretation of metacharacters by the shell. Whereas the backslash is used to escape a single character, the quotes can be used to protect a string of characters. There are some general rules for using quotes:
Quotes are paired and must be matched on a line. The backslash character can be used to escape a newline so that a quote can be matched on the next line.
Single quotes will protect double quotes, and double quotes will protect single quotes.
Single quotes protect all metacharacters from interpretation, with the exception of the history character (!).
Double quotes protect all metacharacters from interpretation, with the exception of the history character (!), the variable substitution character ($), and the backquotes (used for command substitution).
The backslash is used to quote a single character and is the only character that can be used to escape a history character sequence (such as !! or !string or !5). Often the backslash is used to escape the newline character. The special tcsh variable backslash_quote can be used for quoting quotes and backslashes, but will not work in csh scripts. (See Example 13.80.)
1 > echo Who are you? echo: No match. 2 > echo Who are you\? Who are you? 3 > echo This is a very,very long line and this is where\ ? I break the line. This is a very, very long line and this is where I break the line. 4 > echo "\abc" \abc > echo '\abc' \abc > echo \\abc \abc 5 > echo 'I can\'t help it!' Unmatched '. 6 > set backslash_quote > echo 'I can't help it!' I can't help it!
EXPLANATION
|
Single quotes must be matched on the same line and will escape all metacharacters with the exception of the history (bang) character (!), which is not protected because the shell evaluates history before it does quotes (but not before backslashes).
1 > echo 'I need $5.00' I need $5.00 2 > cp file1 file2 > echo 'I need $500.00 now!!' echo 'I need $500.00 nowcp file1 file2' 3 > echo 'I need $500.00 now\!\!' I need $500.00 now!! 4 > echo 'This is going to be a long line so Unmatched '. 5 > echo 'This is going to be a long line so \ ? I used the backslash to suppress the newline' This is going to be a long line so I used the backslash to suppress the newline
EXPLANATION
|
Double quotes must be matched, will allow variable and command substitution, and hide everything else except the history (bang (!)). The backslash will not escape the dollar sign when enclosed in double quotes.
1 > set name = Bob > echo "Hi $name" Hi Bob 2 > echo "I don't have time." I don't have time. 3 > echo "WOW!!" # Watch the history metacharacter! echo "Wowecho "Wow!!"" 4 > echo "WOW\!\!" Wow!! 5 > echo "I need \$5.00" I need \.00
EXPLANATION
|
As long as the quoting rules are adhered to, double quotes and single quotes can be used in a variety of combinations in a single command.
1 > set name = Tom 2 > echo "I can't give $name" ' $5.00\!\!' I can't give Tom $5.00!! 3 > echo She cried, \"Oh help me\!\!'" ', $name. She cried, "Oh help me!!", Tom.
EXPLANATION
|
In a more complex command, it is often difficult to match quotes properly unless you follow the steps listed here. (See Appendix C.)
Know the UNIX command and its syntax. Before variable substitution, hard code the values into the command line to see if you get the expected results.
> awk -F: '/^Zippy Pinhead/{print "Phone is " $2}' datafile Phone is 408-123-4563
If the UNIX command worked correctly, then plug in the variables. At this point, do not remove or change any quotes. Simply put the variables in place of the words they represent. In this example, replace Zippy Pinhead with $name.
> set name = "Zippy Pinhead" > awk -F: '/^$name/{print "Phone is " $2}' datafile
Play the quoting game as follows: Starting at the left-hand side with the first single quote, insert a matching single quote just before the dollar sign in $name. Now you have a set of matched quotes.
awk -F: '/^'$name/{print "Phone is " $2}' datafile
Now, right after the last letter, e in $name, place another single quote. (Believe me, this works.) This quote matches the quote after the closing curly brace.
> awk -F: '/^'$name'/{print "Phone is " $2}' datafile
Count the number of single quotes, starting at the left-hand side. You have four, a nice even number. Everything within each set of single quotes is ignored by the shell. The quotes are matched as follows:
Last step: Double quote the variables. Surround each variable very snugly within a set of double quotes. The double quotes protect the whitespace in the expanded variable; for example, the space in Zippy Pinhead is protected.
The :x and :q modifiers are used when it's necessary to quote variables.
Quoting with the :q Modifier. The :q modifier is used to replace double quotes.
1 > set name = "Daniel Savage" 2 > grep $name:q database same as 3 > grep "$name" database 4 > set food = "apple pie" 5 > set dessert = ( $food "ice cream") 6 > echo $#dessert 3 7 > echo $dessert[1] apple 8 > echo $dessert[2] pie 9 > echo $dessert[3] ice cream 10 > set dessert = ($food:q "ice cream") 11 > echo $#dessert 2 12 > echo $dessert[1] apple pie 13 > echo $dessert[2] ice cream
EXPLANATION
|
Quoting with the :x Modifier. If you are creating an array and any of the words in the list contain metacharacters, :x prevents the shell from interpreting the metacharacters when performing variable substitution.
1 > set things = "*.c a?? file[1 5]" > echo $#things 1 2 > set newthings = ( $things ) set: No match 3 > set newthings = ( $things:x ) 4 > echo $#newthings 3 5 > echo "$newthings[1] $newthings[2] $newthings[3] " *.c a?? file[1-5] 6 > grep $newthings[2]:q filex
EXPLANATION
|
Rather than residing on disk like UNIX executable commands, built-in commands are part of the TC shell's internal code and are executed from within the shell. If a built-in command occurs as any component of a pipeline except the last, it is executed in a subshell. The tcsh command, aptly called builtins, lists all the built-in commands:
1 > builtins : @ alias alloc bg bindkey break breaksw builtins case cd chdir complete continue default dirs echo echotc else end endif endsw eval exec exit fg filetest foreach glob goto hashstat history hup if jobs kill limit log login logout ls-F nice nohup notify onintr popd printenv pushd rehash repeat sched set setenv settc setty shift source stop suspend switch telltc time umask unalias uncomplete unhash unlimit unset unsetenv wait where which while
See Table 13.24 for a list of built-in commands.
Built-In Command | Meaning | |||
---|---|---|---|---|
: | Interprets null command, but performs no action. | |||
alias [name [wordlist]] | A nickname for a command. Without arguments, prints all aliases; with a name, prints the name for the alias; with a name and wordlist, sets the alias. | |||
alloc | Displays amount of dynamic memory acquired, broken down into used and free memory. Varies across systems. | |||
bg [%job] %job & | Runs the current or specified jobs in the background. A synonym for the bg built-in command. | |||
bindkey [-l|-d|-e|-v|-u] (+) bindkey [-a] [-b] [-k] [-r] [- -] key | Without options, the first form lists all bound keys and the editor command to which each is bound, the second form lists the editor command to which key is bound, and the third form binds the editor command command to key. Options include: | |||
bindkey [-a] [-b] [-k] [-c|-s] [- -] key command | -l | Lists all editor commands and a short description of each. | ||
-d | Binds all keys to the standard bindings for the default editor. | |||
-e | Binds all keys to the standard GNU emacs-like bindings. | |||
-v | Binds all keys to the standard vi-like bindings. | |||
-a | Lists or changes key-bindings in the alternative key map. This is the key map used in vi command mode. | |||
-b | This key is interpreted as a control character written as ^character (e.g., ^A) or C-character (e.g., C-A), a meta- character written M-character (e.g., M-A), a function key written F-string (e.g., F-string), or an extended prefix key written X-character (e.g., X-A). | |||
-k | This key is interpreted as a symbolic arrow key name, which may be one of down, up, left, or right. | |||
-r | Removes key's binding. Be careful: bindkey-r does not bind key to self-insert-command (q.v.), it unbinds key completely. | |||
-c | This command is interpreted as a built-in or external command, instead of an editor command. | |||
-s | This command is taken as a literal string and treated as terminal input when key is typed. Bound keys in commands are themselves reinterpreted, and this continues for 10 levels of interpretation. | |||
- - | -Forces a break from option processing, so the next word is taken as a key even if it begins with a hyphen (-). | |||
-u | (or any invalid option) Prints a usage message. This key may be a single character or a string. If a command is bound to a string, the first character of the string is bound to sequence-lead-in and the entire string is bound to the command. Control characters in key can be literal (they can be typed by preceding them with the editor command quoted-insert, normally bound to ^V) or written caret-character style, e.g., ^A. Delete is written ^? (caret-question mark). Key and command can contain backslashed escape sequences (in the style of System V echo) as follows: | |||
\a Bell | \f Form feed | \t Horizontal tab | \b Backspace | |
\n Newline | \v Vertical tab | \e Escape | \r Carriage return | |
\nnn The ASCII character corresponding to the octal number nnn. | ||||
\ nullifies the special meaning of the following character, if it has any, notably backslash (\) and caret (^). | ||||
break | Breaks out of the innermost foreach or while loop. | |||
breaksw | Breaks from a switch, resuming after the endsw. | |||
builtins | Prints the names of all built-in commands. | |||
bye | A synonym for the logout built-in command. Available only if the shell was so compiled; see the version shell variable. | |||
case label: | A label in a switch statement. | |||
cd [dir] | Changes the shell's working directory to dir. If no argument is given, changes to the home directory of the user. | |||
cd [-p] [-l] [-n|-v] [name] | If a directory name is given, changes the shell's working directory to name. If not, changes to home. If name is - it is interpreted as the previous working directory.
| |||
chdir | A synonym for the cd built-in command. | |||
complete [command [word/pattern/list[:select]/[[suffix]/] ]] | Without arguments, lists all completions. With command, lists completions for command. With command and word etc., defines completions. (See "Programming Completions" on page 866.) | |||
continue | Continues execution of the nearest enclosing while or foreach. | |||
default: | Labels the default case in a switch statement. The default should come after all case labels. | |||
dirs [-l] [-n|-v] dirs -S|-L [filename] dirs -c | The first form prints the directory stack. The top of the stack is at the left and the first directory in the stack is the current directory. -l, ~ or ~name in the output is expanded explicitly to home or the pathname of the home directory for user name.
| |||
In either case, dirsfile is used if filename is not given and ~/.cshdirs is used if dirsfile is unset.
| ||||
echo [-n] list | Writes the words in list to the shell's standard output, separated by SPACE characters. The output is terminated with a NEWLINE unless the -n option is used. | |||
echo [-n] word | Writes each word to the shell's standard output, separated by spaces and terminated with a newline. The echo_style shell variable may be set to emulate (or not) the flags and escape sequences of the BSD and/or System V versions of echo. | |||
echotc [-sv] arg | Exercises the terminal capabilities in args. For example, echotc home sends the cursor to the home position. If arg is baud, cols, lines, meta, or tabs, prints the value of that capability. With -s, nonexistent capabilities return the empty string rather than causing an error. With -v, messages are verbose. | |||
else if (expr2) then | See "The if/else if Statements" on page 401. | |||
else end endif endsw | See the description of the foreach, if, switch, and while statements below. | |||
end | Executes the commands between the while and the matching end while expr evaluates nonzero. while and end must appear alone on their input lines. break and continue may be used to terminate or continue the loop prematurely. If the input is a terminal, the user is prompted the first time through the loop as with foreach. | |||
eval arg | Treats the arguments as input to the shell and executes the resulting command(s) in the context of the current shell. This is usually used to execute commands generated as the result of command or variable substitution, since parsing occurs before these substitutions. | |||
eval command | Runs command as standard input to the shell and executes the resulting commands. This is usually used to execute commands generated as the result of command or variable substitution, since parsing occurs before these substitutions (e.g., eval tset -s options). | |||
exec command | Executes command in place of the current shell, which terminates. | |||
exit [(expr)] | Exits the shell, either with the value of the status variable or with the value specified by expr. | |||
fg [% job ] %job | Brings the current or specified job into the foreground. A synonym for the fg built-in command. | |||
filetest -op file | Applies op (which is a file inquiry operator) to each file and returns the results as a space-separated list. | |||
foreach name (wordlist)
end | See "The foreach Loop" on page 412. | |||
foreach var (wordlist) | See "The foreach Loop" on page 412. | |||
getspath | Prints the system execution path. (TCF only) (tcsh only) | |||
getxvers | Prints the experimental version prefix. (TCF only) (tcsh only) | |||
glob wordlist | Performs filename expansion on wordlist. Like echo, but no escapes (\) are recognized. Words are delimited by null characters in the output. | |||
goto label | See "The goto" on page 405. | |||
goto word | word is filename and command-substituted to yield a string of the form label. The shell rewinds its input as much as possible, searches for a line of the form label:, possibly preceded by blanks or tabs, and continues execution after that line. | |||
hashstat | Prints a statistics line indicating how effective the internal hash table has been at locating commands (and avoiding execs). An exec is attempted for each component of the path where the hash function indicates a possible hit, and in each component that does not begin with a backslash. | |||
history [-hTr] [n] history -S|-L|-M [filename] history -c | The first form prints the history event list. If n is given, only the n most recent events are printed or saved. With -h, the history list is printed without leading numbers. If -T is specified, timestamps are printed in comment form. (This can be used to produce files suitable for loading with history -L or source -h.) With -r, the order of printing is most recent first rather than oldest first. (See "History".) With -c, clears the history list. | |||
hup [command] | With command, runs command such that it will exit on a hangup signal and arranges for the shell to send it a hangup signal when the shell exits. Note that commands may set their own response to hangups, overriding hup. Without an argument (allowed only in a shell script), causes the shell to exit on a hangup for the remainder of the script. | |||
if (expr) command | If expr evaluates true, then command is executed. Variable substitution on command happens early, at the same time it does for the rest of the if command. Command must be a simple command, not an alias, a pipeline, a command list or a parenthesized command list, but it may have arguments. Input/output redirection occurs even if expr is false and command is thus not executed; this is a bug. | |||
if (expr) then
else if (expr2) then
else
endif | If the specified expr is true then the commands to the first else are executed; otherwise if expr2 is true then the commands to the second else are executed, etc. Any number of else if pairs are possible; only one endif is needed. The else part is likewise optional. (The words else and endif must appear at the beginning of input lines; the if must appear alone on its input line or after an else.) | |||
inlib shared-library | Adds each shared-library to the current environment. There is no way to remove a shared library. (Domain/OS only) | |||
jobs [-l] | Lists the active jobs under job control. With -l, lists IDs in addition to the normal information. | |||
kill [-sig] [pid] [%job] kill -l | Sends the TERM (terminate) signal, by default or by the signal specified, to the specified ID, the job indicated, or the current job. Signals are given either by number or name. There is no default. Typing kill does not send a signal to the current job. If the signal being sent is TERM (terminate) or HUP (hangup), then the job or process is sent a CONT (continue) signal as well. With -l, lists the signal names that can be sent. | |||
limit [-h] [resource [max-use]] | Limits the consumption by the current process or any process it spawns, each not to exceed max-use on the specified resource. If max-use is omitted, print the current limit; if resource is omitted, display all limits. With -h, uses hard limits instead of the current limits. Hard limits impose a ceiling on the values of the current limits. Only the superuser may raise the hard limits. Resource is one of: cputime, maximum CPU seconds per process; filesize, largest single file allowed; datasize, maximum data size (including stack) for the process; stacksize, maximum stack size for the process; coredump, maximum size of a core dump; and descriptors, maximum value for a file descriptor. | |||
log | Prints the watch shell variable and reports on each user indicated in watch who is logged in, regardless of when they last logged in. See also watchlog. | |||
login | Terminates a login shell, replacing it with an instance of /bin/login. | |||
login [username|-p] | Terminates a login shell and invokes login. The .logout file is not processed. If username is omitted, login prompts for the name of a user. With -p, preserves the current environment (variables). | |||
logout | Terminates a login shell. | |||
ls -F [-switch ] [file ] | Lists files like ls -F, but much faster. It identifies each type of special file in the listing with a special character: | |||
/ | Directory | |||
* | Executable | |||
# | Block device | |||
| | Named pipe (systems with named pipes only) | |||
= | Socket (systems with sockets only) | |||
+ | Hidden directory (AIX only) or context-dependent (HP/UX only) | |||
@ | Symbolic link (systems with symbolic links only) | |||
: | Network special (HP/UX only) | |||
If the listlinks shell variable is set, symbolic links are identified in more detail (only, of course, on systems which have them): | ||||
@ | Symbolic link to a nondirectory | |||
> | Symbolic link to a directory | |||
& | Symbolic link to nowhere | |||
The ls -F built-in can list files using different colors depending on the filetype or extension. | ||||
migrate [-site] pid|%jobid migrate -site | The first form migrates the process or job to the site specified or the default site determined by the system path. The second form is equivalent to migrate -site $$. It migrates the current process to the specified site. Migrating the shell itself can cause unexpected behavior, since the shell does not like to lose its tty. (TCF only) | |||
@ @ name = expr @ name[index] = expr @ name++|- - @ name[index]++|- - | The first form prints the values of all shell variables. The second form assigns the value of expr to name. The third form assigns the value of expr to the indexth component of name; both name and its indexth component must already exist. The fourth and fifth forms increment (++) or decrement (- -) name or its indexth component. | |||
newgrp [-] group | Equivalent to exec newgrp. Available only if the shell was so compiled; see the version shell variable. | |||
nice [+number][command] | Sets the scheduling priority for the shell to number, or, without number, to 4. With command, runs command at the appropriate priority. The greater the number, the less CPU the process gets. The superuser may specify negative priority by using nice -number . Command is always executed in a subshell, and the restrictions placed on commands in simple if statements apply. | |||
nohup [command] | Runs command with HUPs (hangups) ignored. With no arguments, ignores HUPs throughout the remainder of a script. | |||
notify [%job] | Notifies the user asynchronously when the status of the current or of a specified job changes. | |||
onintr [- | label] | Controls the action of the shell on interrupts. With no arguments, onintr restores the default action of the shell on interrupts. (The shell terminates shell scripts and returns to the terminal command input level.) With the minus sign argument, the shell ignores all interrupts. With a label argument, the shell executes a goto label when an interrupt is received or a child process terminates because it was interrupted. | |||
popd [+n] | Pops the directory stack and cd to the new top directory. The elements of the directory stack are numbered from zero, starting at the top. With +n, discard the nth entry in the stack. | |||
printenv [name] | Prints the names and values of all environment variables or, with name, the value of the environment variable name. | |||
pushd [+n | dir] | Pushes a directory onto the directory stack. With no arguments, exchanges the top two elements. With +n, rotates the nth entry to the top of the stack and cd to it. With dir, pushes the current working directory onto the stack and changes to dir. | |||
rehash | Recomputes the internal hash table of the contents of directories listed in the path variable to account for new commands added. | |||
repeat count command | Repeats command count times. | |||
rootnode //nodename | Changes the rootnode to //nodename, so that / will be interpreted as //nodename. (Domain/OS only) | |||
sched sched [+]hh:mm command sched -n | The first form prints the scheduled-event list. The sched shell variable may be set to define the format in which the scheduled-event list is printed. The second form adds command to the scheduled-event list. | |||
set set name set name=word set [-r] [-f|-l] name=(wordlist) (+) set name[index]=word set -r set -r name set -r name=word | The first form of the command prints the value of all shell variables. Variables which contain more than a single word print as a parenthesized word list. The second form sets name to the null string. The third form sets name to the single word. The fourth form sets name to the list of words in wordlist. In all cases the value is command and filename expanded. If -r is specified, the value is set read-only. If -f or -l are specified, set only unique words keeping their order. -f prefers the first occurrence of a word, and -l the last occurrence of the word. The fifth form sets the index'th component of name to word; this component must already exist. The sixth form lists the names (only) of all shell variables which are read-only (tcsh only). The seventh form makes name read-only, whether or not it has a value (tcsh only). The eighth form is the same as the third form, but makes name read-only at the same time (tcsh only). | |||
set [var [= value]] | See "Variables". | |||
setenv [VAR [word]] | See "Variables". The most commonly used environment variables, USER, TERM, and PATH, are automatically imported to and exported from the csh variables user, term, and path; there is no need to use setenv for these. In addition, the shell sets the PWD environment variable from the csh variable cwd whenever the latter changes. | |||
setenv [name [value]] | Without arguments, prints the names and values of all environment variables. Given name, sets the environment variable name to value or, without value, to the null string. | |||
setpath path | Equivalent to setpath. (Mach only) | |||
setspath LOCAL|site|cpu | Sets the system execution path. (TCF only) | |||
settc cap value | Tells the shell to believe that the terminal capability cap has the value value. No sanity checking is done. Concept terminal users may have to settc xn no to get proper wrapping at the rightmost column. | |||
setty [-d|-q|-x] [-a] [[+|-]mode] | Controls which tty modes the shell does not allow to change. -d, -q, or -x tells setty to act on the edit, quote, or execute set of tty modes, respectively; without -d, -q, or -x, execute is used. Without other arguments, setty lists the modes in the chosen set which are fixed on (+mode) or off (-mode). The available modes, and thus the display, vary from system to system. With -a, lists all tty modes in the chosen set whether or not they are fixed. With +mode, -mode, or mode, fixes mode on or off or removes control from mode in the chosen set. For example, setty +echok echoe fixes echok mode on and allows commands to turn echoe mode on or off, both when the shell is executing commands. | |||
setxvers [string] | Sets the experimental version prefix to string, or removes it if string is omitted. (TCF only) | |||
shift [variable] | The components of argv, or variable, if supplied, are shifted to the left, discarding the first component. It is an error for variable not to be set, or to have a null value. | |||
source [-h] name | Reads commands from name. Source commands may be nested, but if they are nested too deeply, the shell may run out of file descriptors. An error in a sourced file at any level terminates all nested source commands. Used commonly to reexecute the .login or .cshrc files to ensure variable settings are handled within the current shell, i.e., shell does not create a child shell (fork). With -h, places commands from the filename on the history list without executing them. | |||
stop [%job] | Stops the current or specified background job. | |||
suspend | Stops the shell in its tracks, much as if it had been sent a stop signal with ^Z. This is most often used to stop shells started by su. | |||
switch (string) | See "The switch Command" on page 409. | |||
telltc | Lists the values of all terminal capabilities. | |||
time [command] | With no argument, prints a summary of time used by this shell and its children. With an optional command, executes command and print a summary of the time it uses. | |||
umask [value] | Displays the file creation mask. With value, sets the file creation mask. Value, given in octal, is xored with the permissions of 666 for files and 777 for directories to arrive at the permissions for new files. Permissions cannot be added via umask. | |||
unalias pattern | Removes all aliases whose names match pattern. unalias * thus removes all aliases. It is not an error for nothing to be unaliased. | |||
uncomplete pattern | Removes all completions whose names match pattern. uncomplete * thus removes all completions. | |||
unhash | Disables the internal hash table. | |||
universe universe | Sets the universe to universe. (Masscomp/RTU only) | |||
unlimit [-h] [resource] | Removes the limitation on resource or, if no resource is specified, all resource limitations. With -h, the corresponding hard limits are removed. Only the superuser may do this. | |||
unsetenv pattern | Removes all environment variables whose names match pattern. unsetenv * thus removes all environment variables; this is a bad idea. If there is no pattern to be unsetenved, no error will result from this built-in. | |||
unsetenv variable | Removes variable from the environment. Pattern matching, as with unset, is not performed. | |||
@ [var =expr] @ [var[n] =expr] | With no arguments, displays the values for all shell variables. With arguments, the variable var, or the nth word in the value of var, is set to the value that expr evaluates to. | |||
ver [systype [command]] | Without arguments, prints SYSTYPE. With systype, sets SYSTYPE to systype. With systype and command, executes command under systype. systype may be bsd4.3 or sys5.3. (Domain/OS only) | |||
wait | Waits for background jobs to finish (or for an interrupt) before prompting. | |||
warp universe | Sets the universe to universe. (Convex/OS only) | |||
watchlog | An alternate name for the log built-in command (q.v.). Available only if the shell was so compiled; see the version shell variable. | |||
where command | Reports all known instances of command, including aliases, built-ins, and executables in path. | |||
which command | Displays the command that will be executed by the shell after substitutions, path searching, etc. The built-in command is just like which, but it correctly reports tcsh aliases and built-ins and is 10 to 100 times faster. | |||
while (expr) | See "The while Loop" on page 415. |
If set, each of the TC shell aliases executes automatically at the indicated time. They are all initially undefined.
beepcmd | Runs when the shell wants to ring the terminal bell. |
cwdcmd | Runs after every change of working directory. |
periodic | Runs every tperiod minutes; e.g., > set tperiod = 30 > alias periodic date |
precmd | Runs just before each prompt is printed; e.g., alias precmd date. |
The built-in shell variables have special meaning to the shell and are used to modify and control the way many of the shell commmands behave. They are local variables and therefore most of them are set in the .tcshrc file if they are to be passed on to and affect child TC shells.
When the shell starts up, it automatically sets the following variables: addsuffix, argv, autologout, command, echo_style, edit, gid, group, home, loginsh, oid, path, prompt, prompt2, prompt3, shell, shlvl, tcsh, term, tty, uid, user, and version. Unless the user decides to change them, these variables will remain fixed. The shell also keeps track of and changes special variables that may need periodic updates, such as, cwd, dirstack, owd, and status, and when the user logs out, the shell sets the logout variable.
Some of the local variables have a corresponding environment variable of the same name. If one of the environment or local variables are affected by a change in the user's environment, the shell will synchronize the local and environment variables[10] so that their values always match. Examples of cross-matched variables are afuser, group, home, path, shlvl, term, and user. (Although cwd and PWD have the same meaning, they are not cross-matched. Even though the syntax is different for the path and PATH variables, they are automatically crossed-matched if either one is changed.)
Variable | Effect | |
---|---|---|
addsufix | For filename completion, adds slashes at the end of directories and space to the end of normal files if they are matched. Set by default. | |
afsuser | If set, autologout's autolock feature uses its value instead of the local username for kerberos authentication. | |
ampm | If set, all times are shown in 12-hour AM/PM format. | |
argv | An array of command line arguments to the shell; also represented as $1, $2, etc. | |
autocorrect | Invokes the spell checker before each attempt at filename, command, or variable completion. | |
autoexpand | If set, the expand-history editor command is invoked automatically before each completion attempt. | |
autolist | If set, possibilities are listed after an ambiguous completion. If set to ambiguous, possibilities are listed only when no new characters are added by completion. | |
autologout | Its argument is the number of minutes of inactivity before automatic logout; the second optional argument is the number of minutes before automatic locking causes the screen to lock. | |
backslash_quote | If set, a backslash will always quote itself, a single quote, or a double quote. | |
cdpath | A list of directories in which cd should search for subdirectories if they aren't found in the current directory. | |
color | Enables color display for the built-in command, ls -F and passes - -color=auto to ls. | |
complete | If set to enhance, completion ignores case, considers periods, hyphens, and underscores to be word separators, and hyphens and underscores to be equivalent. | |
correct | If set to cmd, commands are automatically spelling-corrected. If set to complete, commands are automatically completed. If set to all, the entire command line is corrected. | |
cwd | The full pathname of the current working directory. | |
dextract | If set, pushd +n extracts the nth directory from the directory stack rather than rotating it to the top. | |
dirsfile | The default location in which dirs -S and dirs -L look for a history file. If unset, ~/.cshdirs is used. | |
dirstack | A list of all directories on the directory stack. | |
dunique | Will not allow pushd to keep duplicate directory entries on the stack. | |
echo | If set, each command with its arguments is echoed just before it is executed. Set by the -x command line option. | |
echo-style | Sets the style for echo. If set to bsd will not echo a newline if the first argument is -n; if set to sysv, recognizes backslashed escape sequences in echo strings; if set to both, recognizes both the -n flag and backslashed escape sequences; the default, and if set to none, recognizes neither. | |
edit | Sets the command-line editor for interactive shells; set by default. | |
ellipsis | If set, the %c/%. and %C prompt sequences (see the "The Shell Prompts") indicate skipped directories with an ellipsis ( ) instead of /<skipped>. | |
fignore | Lists filename suffixes to be ignored by completion. | |
filec | In tcsh, completion is always used and this variable is ignored. If set in csh, filename completion is used. | |
gid | The user's read group ID number. | |
group | The user's group name. | |
histchars | A string value determining the characters used in history substitution. The first character of its value is used as the history substitution character to replace the default character, !. The second character of its value replaces the character ^ in quick substitutions. | |
histdup | Controls handling of duplicate entries in the history list. Can be set to all (removes all duplicates) , prev (removes the current command if it duplicates the previous command), or erase (inserts the current event for an older duplicate event). | |
histfile | The default location in which history -S and history -L look for a history file. If unset, ~/.history is used. | |
histlit | Enters events on the history list literally; i.e., unexpanded by history substitution. | |
history | The first word indicates the number of history events to save. The optional second word (+) indicates the format in which history is printed. | |
home | The home directory of the user; same as ~. | |
ignoreeof | If logging out by pressing Control-D, prints Use exit to leave tcsh. Prevents inadvertently logging out. | |
implicitcd | If set, the shell treats a directory name typed as a command as though it were a request to change to that directory and changes to it. | |
inputmode | If set to insert or overwrite, puts the editor into that input mode at the beginning of each line. | |
listflags | If set to x, a, or A, or any combination (e.g., xA), values are used as flags to ls -F, making it act like ls -xF, ls -Fa, ls -FA, or any combination of those flags. | |
listjobs | If set, all jobs are listed when a job is suspended. If set to long, the listing is in long format. | |
listlinks | If set, the ls -F built-in command shows the type of file to which each symbolic link points. | |
listmax | The maximum number of items that the list-choices editor command will list without asking first. | |
listmaxrows | The maximum number of rows of items which the list-choices editor command will list without asking first. | |
loginsh | Set by the shell if it is a login shell. Setting or unsetting it within a shell has no effect. See also shlvl later in this table. | |
logout | Set by the shell to normal before a normal logout, automatic before an automatic logout, and hangup if the shell was killed by a hangup signal. | |
The names of the files or directories to check for incoming mail. After 10 minutes if new mail has come in, will printYou have new mail. | ||
matchbeep | If set to never, completion never beeps; if set to nomatch, completion beeps only when there is no match; and when set to ambiguous, beeps when there are multiple matches. | |
nobeep | Disables all beeping. | |
noclobber | Safeguards against the accidental removal of existing files when redirection is used; e.g., ls > file. | |
noglob | If set, inhibits filename and directory stack substitutions when using wildcards. | |
nokanji | If set and the shell supports Kanji (see the version shell variable), it is disabled so that the Meta key can be used. | |
nonomatch | If set, a filename substitution or directory stack substitution that does not match any existing files is left untouched rather than causing an error. | |
nostat | A list of directories (or glob patterns that match directories) that should not be stated during a completion operation. This is usually used to exclude directories which take too much time tostat. | |
notify | If set, the shell announces job completions asynchronously instead of waiting until just before the prompt appears. | |
oid | The user's real organization ID. (Domain/OS only) | |
owd | The old or previous working directory. | |
path | A list of directories in which to look for executable commands. path is set by the shell at startup from the PATH environment variable or, if PATH does not exist, to a system-dependent default something like /usr/local/bin /usr/bsd/bin /usr/bin. | |
printexitvalue | If set and an interactive program exits with a nonzero status, the shell prints Exit status. | |
prompt | The string printed before reading each command from the terminal; may include special formatting sequences (See "The Shell Prompts"). | |
prompt2 | The string with which to prompt in while and foreach loops and after lines ending in \. The same format sequences may be used as in prompt; note the variable meaning of %R. Set by default to %R? in interactive shells. | |
prompt3 | The string with which to prompt when confirming automatic spelling correction. The same format sequences may be used as in prompt; note the variable meaning of %R. Set by default to CORRECT>%R (y|n|e|a)? in interactive shells. | |
promptchars | If set (to a two-character string), the %# formatting sequence in the prompt shell variable is replaced with the first character for normal users and the second character for the superuser. | |
pushtohome | If set, pushd without arguments does pushd ~, like cd. | |
pushdsilent | If set, pushd and popd do not print the directory stack. | |
recexact | If set, completion completes on an exact match even if a longer match is possible. | |
recognize_only_executables | If set, command listing displays only files in the path that are executable. | |
rmstar | If set, the user is prompted before rm [23] is executed. | |
rprompt | The string to print on the right-hand side of the screen (after the command input) when the prompt is being displayed on the left. It recognises the same formatting characters as prompt. It will automatically disappear and reappear as necessary, to ensure that command input isn't obscured, and will only appear if the prompt, command input, and itself will fit together on the first line. If edit isn't set, then rprompt will be printed after the prompt and before the command input. | |
savedirs | If set, the shell does dirs -S before exiting. | |
savehist | If set, the shell does history -S before exiting. If the first word is set to a number, at most that many lines are saved. (The number must be less than or equal to history.) If the second word is set to merge, the history list is merged with the existing history file instead of replacing it (if there is one) and sorted by timestamp and the most recent events are retained. | |
sched | The format in which the sched built-in command prints scheduled events; if not given, %h\t%T\t%R\n is used. The format sequences are described above under prompt; note the variable meaning of %R. | |
shell | The file in which the shell resides. This is used in forking shells to interpret files that have execute bits set, but that are not executable by the system. (See the description of built-in and nonbuilt-in command execution.) Initialized to the (system-dependent) home of the shell. | |
shlvl | The number of nested shells. Reset to 1 in login shells. See also loginsh. | |
status | The status returned by the last command. If it terminated abnormally, then 0200 is added to the status. Built-in commands that fail return exit status 1, all other built-in commands return status 0. | |
symlinks | Can be set to several different values to control symbolic link (symlink) resolution. (See tcsh man page for examples.) | |
tcsh | The version number of the shell in the format R.VV.PP, where R is the major release number, VV the current version, and PP the patch level. | |
term | The terminal type. Usually set in ~/.login as described under "Startup". | |
time | If set to a number, then the time built-in executes automatically after each command which takes more than that many CPU seconds. If there is a second word, it is used as a format string for the output of the time built-in. The following sequences may be used in the format string: | |
%U | The time the process spent in user mode in CPU seconds. | |
%S | The time the process spent in kernel mode in CPU seconds. | |
%E | The elapsed (wall clock) time in seconds. | |
%P | The CPU percentage computed as (%U + %S) / %E. | |
%W | Number of times the process was swapped. | |
%X | The average amount in (shared) text space used in KB. | |
%D | The average amount in (unshared) data/stack space used in KB. | |
%K | The total space used (%X + %D) in KB. | |
%M | The maximum memory the process had in use at any time in KB. | |
%F | The number of major page faults (page needed to be brought from disk). | |
%R | The number of minor page faults. | |
%I | The number of input operations. | |
%O | The number of output operations. | |
%r | The number of socket messages received. | |
%s | The number of socket messages sent. | |
%k | The number of signals received. | |
%w | The number of voluntary context switches (waits). | |
%c | The number of involuntary context switches. | |
Only the first four sequences are supported on systems without BSD resource limit functions. The default time format is %Uu %Ss %E %P %X+%Dk %I+%Oio %Fpf+%Ww for systems that support resource usage reporting and %Uu %Ss %E %P for systems that do not. | ||
Under Sequent's DYNIX/ptx, %X, %D, %K, %r, and %s are not available, but the following additional sequences are: | ||
%Y | The number of system calls performed. | |
%Z | The number of pages that are zero-filled on demand. | |
%i | The number of times a process' resident set size was increased by the kernel. | |
%d | The number of times a process' resident set size was decreased by the kernel. | |
%l | The number of read system calls performed. | |
%m | The number of write system calls performed. | |
%p | The number of reads from raw disk devices. | |
%q | The number of writes to raw disk devices. | |
The default time format is %Uu %Ss $E %P %I+%Oio %Fpf+%Ww. Note that the CPU percentage can be higher than 100 percent on multiprocessors. | ||
tperiod | The period, in minutes, between executions of the periodic special alias. | |
tty | The name of the tty, or empty if not attached to one. | |
uid | The user's real user ID. | |
user | The user's login name. | |
verbose | If set, causes the words of each command to be printed, after history substitution (if any). Set by the -v command line option. | |
version | The version ID stamp. It contains the shell's version number (see tcsh), origin, release date, vendor, operating system, etc. |
[23] Adapted from the tcsh manual pages.
Shell Command Line Switches. The TC shell can take a number of command line switches (also called flag arguments) to control or modify its behavior. The command line switches are listed in Table 13.26.
Switch | Meaning |
---|---|
- | Specifies the shell is a login shell. |
-b | Forces a "break" from option processing. Any shell arguments thereafter, will not be treated as options. The remaining arguments will not be interpreted as shell options. Must include this option if shell is set-user-ID. |
-c | If a single argument follows the -c, commands are read from the argument (a filename). Remaining arguments are placed in the argv shell variable. |
-d | The shell loads the directory stack from ~/.cshdirs. |
-Dname[=value] | Sets the environment variable name to value. |
-e | The shell exits if any invoked command terminates abnormally or yields a nonzero exit status. |
-f | Called the fast startup because the shell ignores ~/.tcshrc when starting a new TC shell. |
-F | The shell uses fork instead of vfork to spawn processes. (Convex/OS only) |
-i | The shell is interactive and prompts input, even if it appears to not be a terminal. This option isn't necessary if input and output are connected to a terminal. |
-l | The shell is a login shell if -l is the only flag specified. |
-m | The shell loads ~/.tcshrc even if it does not belong to the effective user. |
-n | Used for debugging scripts. The shell parses commands but does not execute them. |
-q | The shell accepts the SIGQUIT signal and behaves when it is used under a debugger. Job control is disabled. |
-s | Command input is taken from the standard input. |
-t | The shell reads and executes a single line of input. A backslash (\) may be used to escape the newline at the end of this line and continue on to another line. |
-v | Sets the verbose shell variable so that command input is echoed after history substitution. Used to debug shell scripts. |
-x | Sets the echo shell variable so that commands are echoed before execution and after history and variable substitution. Used to debug shell scripts. |
-V | Sets the verbose shell variable before executing the ~/.tcshrc file. |
-X | Sets the echo shell variable before executing the ~/.tcshrc file. |
[*] Adapted from the tcsh manual pages.
1: | What does the init process do? |
2: | What is the function of the login process? |
3: | How do you know what shell you are using? |
4: | How can you change your login shell? |
5: | Explain the difference between the .tcshrc, .cshrc, and .login files. Which one is executed first? |
6: | Edit your .tcshrc file as follows:
|
7: | Type the following: source .tcshrc What does the source command do? |
8: | Edit your .login file as follows:
|
9: | What is the difference between path and PATH? |
1: | In what file are history events stored when you log out? What variable controls the number of history events to be displayed? What is the purpose of the savehist variable? |
2: | Print your history list in reverse. |
3: | Print your history list without line numbers. |
4: | Type the following commands:
|
5: | Type history. What is the output?
Use the history command to reexecute the echo command with only its last argument, c. |
6: | Use history to print and execute the last command in your history list that started with the letter d. |
7: | Execute the last command that started with c. |
8: | Execute the echo command and the last argument from the previous command. |
9: | Use the history substitution command to replace the T in the date command with an H. |
10: | How do you use the bindkey command to start the vi editor for command line editing? |
11: | How do you list the editor commands and what they do? |
12: | How do you see how the editing keys are actually bound? |
13: | Describe what the fignore variable does. |
1: | Type at the prompt: touch ab abc a1 a2 a3 all a12 ba ba.1 ba.2 filex filey AbC ABC ABc2 abc |
2: | Write and test the command that will do the following:
|
1: | What are the names of the three file streams associated with your terminal? |
2: | What is a file descriptor? |
3: | What command would you use to do the following:
|
4: | What happens when you type cp all by itself?
|
5: | Use the find command to find all files, starting from the parent directory, and of type directory. Save the standard output in a file called found and any errors in a file called found.errs. |
6: | What is noclobber? How do you override it? |
7: | Take the output of three commands and redirect the output to a file called gottemall. |
8: | Use a pipe(s) with the ps and wc commands to find out how many processes you are currently running. |
1: | What is the difference between a local variable and an environment variable? |
2: | How do you list all local variables? Environmental variables? |
3: | In what initialization file would you store local variables? Why? |
4: | Create an array called fruit. Put five kinds of fruit in the array.
|
5: | Describe the difference between a wordlist and a string. |
[1] The T in tcsh has origins dating back to the TENEX and TOP-10s operating systems used by DEC for its PDP-10 computer. These systems had a form of command completion for the monitor. The creator of the tcsh admired features of these systems, and hence, added the T to the C shell.
[2] See tutorial at www.tac.nyc.ny.us/mirrors/tcsh-book.
[3] The order in which these files are read can be changed when tcsh is compiled.
[4] Do not confuse the search path variable with the cdpath variable set in the cshrc file.
[5] On machines without vfork(2), prints the number and size of hash buckets.
[6] The length of the command line can be 256 characters or more.
[7] The name of the .history file can be changed by assigning the new name to the histfile shell variable.
[8] The tcsh \1 man page warns that spelling correction is not guaranteed to work the way you may intend and is provided as an experimental feature.
[9] The tcsh man page says that a command in the scheduled-event list is executed just before the first prompt is printed after the time when the command is scheduled. If it so happens that the exact time when the command is to be run is missed, an overdue command will execute at the next prompt.
[10] This is true unless the variable is a read-only variable, and then there will be no synchronization.
CONTENTS |