Chapter 13. The Interactive TC Shell

CONTENTS
  •  13.1 Introduction
  •  13.2 The TC Shell Environment
  •  13.3 Command Line Shortcuts
  •  13.4 Job Control
  •  13.5 Metacharacters
  •  13.6 Redirection and Pipes
  •  13.7 Variables
  •  13.8 Arrays
  •  13.9 Special Variables and Modifiers
  •  13.10 Command Substitution
  •  13.11 Quoting
  •  13.12 Built-In Commands
  •  TC SHELL LAB EXERCISES

graphics/ch13.gif

13.1 Introduction

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.

13.1.1 Versions of 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' 
Example 13.1
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 

13.1.2 Startup

Before the TC shell displays a prompt, it is preceded by a number of processes. See Figure 13.1.

Figure 13.1. System startup and the TC shell.

graphics/13fig01.gif

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.

Figure 13.2. If any of these initialization files exist, they are sourced in this sequence.

graphics/13fig02.gif

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.

13.2 The TC Shell Environment

13.2.1 Initialization Files

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.

Example 13.2
# /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

  1. $?PATH is a test to see if the PATH variable has been set; it returns 1 if true.

  2. If the PATH variable has been set, /usr/X11R6/bin is appended to it. This is a directory that contains the X windows files.

  3. If the PATH variable has not been previously set, this line sets it to /bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin

  4. This line checks to see if the prompt has been set.

  5. When you place the expression in square brackets, the expression will be tested and if the result of the expression is true, a zero exit status is returned; otherwise a nonzero exit status is returned. If the value of the SHELL environment variable is /bin/tcsh, the exit status will be 0.

  6. The status variable contains the exit status of the last command executed, which in this example, is the previous test on line 5.

  7. If the status from the last command was zero, the prompt for the /bin/tcsh is set. The prompt will be set to the user's name followed by an @ symbol, the hostname, and the current working directory (all enclosed in [ ] ), followed by a dollar sign; e.g., [ ellie@homebound ~ ]$

  8. If the status was nonzero, the else branches program control to line 9.

  9. This line sets the prompt for the standard csh program. It will print the user's name (id -un), an @ symbol, and the short name for his host machine, i.e., the hostname cut at the first dot, and a $.

  10. The endif terminates the inner if block.

  11. The size of core files (usually created when a program crashes for some illegal system operation) is limited to 1,000,000 bytes. Core files are created if you abort a running program with Control-\.

  12. If the group ID number and the user ID number are the same, and the user ID number is greater than 14, then the next line will be executed; otherwise, the line under the else will be executed. Typically, user IDs below 14 are for special users, such as root, daemon, adm, lp, etc. (See /etc/passwd. The user ID is in field number 3.)

  13. If the test in the previous line returned a nonzero exit status, line 14 is executed, else line 15 is executed.

  14. The umask command sets the file creation mask; i.e., the initial permissions for files and directories when created. Directories will get 755 (rwxr-xr-x) and files will get 644 (rw-r--r--) when they are created.

  15. Umask is set so that when a directory is created, its permissions will be 775 (rwxrwxr-x) and files will get 664 (rw-rw-r--).

  16. The environment variable HOSTNAME is assigned the output of the /bin/hostname command.

  17. The history variable is set to 1000. When commands are typed at the command line, they are saved in a history list. When you set the history variable to 1000, no more than 1,000 commands will be displayed when the history command is typed.

  18. The test command returns zero exit status if the /etc/profile.d directory exists, and nonzero if it doesn't.

  19. If the status is 0, the directory exists, and the program branches to line 20.

  20. The nonomatch variable is set to prevent the shell from sending an error message if any of its special metacharacters (*, ?, []) cannot be matched.

  21. The foreach loop assigns each file with a .csh extension (*.csh) in the /etc/profile.d directory to the variable i, in turn, looping until each file has been tested (lines 22 24).

  22. If the filename assigned to variable i is a regular file (-f), then go to the next line.

  23. If the test returned a 0 status (true), then source the file; i.e., execute it in the context of the current environment.

  24. The end keyword marks the end of the loop body.

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.

Example 13.3
(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

  1. If the prompt has been set ($?prompt), the shell is running interactively; i.e., it is not running in a script. Prompts are set only for interactive shells.

  2. The primary prompt is set to the number of the current history event, the name stardust, and a > character. This will change the > prompt, the default.

  3. The history variable is set to 100. This controls the number of history events that will appear on the screen. The last 100 commands you entered will be displayed when you type history. (See "History".)

  4. Normally, when you log out, the history list is cleared. The savehist variable allows you to save a specified number of commands from the end of the history list. In this example, the last five commands will be saved in a file in your home directory, the .history file, so that when you log in again, the shell can check to see if that file exists and put the history lines saved at the top of the new history list.

  5. The noclobber variable is set to protect the user from inadvertently removing files when using redirection. For example, sort myfile > myfile will destroy myfile. With noclobber set, the message file exists will appear on the screen if you attempt to redirect output to an existing file.

  6. If the tcsh variable rmstar is set, the user will be asked if he really wants to remove all his files after entering rm *; i.e., he is given a chance to save himself from removing all files in his current working directory.

  7. The cdpath variable is assigned a list of path elements. When changing directories, if you specify just the directory name, and that directory is not a subdirectory directly below the current working directory, the shell will search the cdpath directory entries to see if it can find the directory in any of those locations and then will change the directory.

  8. The ignoreeof variable prevents you from logging out with ^D (Control-D). UNIX utilities that accept input from the keyboard, such as the mail program, are terminated by pressing ^D. Often, on a slow system, the user will be tempted to press ^D more than once. The first time, the mail program would be terminated; the second time, the user is logged out. By setting ignoreeof, you are required to type logout to log out.

  9. The aliases are set to give a shorthand notation for a single command or group of commands. Now when you type the alias, the command(s) assigned to it will be executed. The alias for the more command is m. Every time you type m, the more command is executed. The status alias prints the date and a summary of the user's disk usage. The cd alias creates a new prompt every time the user changes directories. The new prompt will contain the number of the current history event (\!*) and the current working directory ($cwd) surrounded by < >. (See "Aliases".)

  10. The endif marks the end of the block of statements following the if construct on line 1.

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.

Example 13.4
(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

  1. The stty command sets options for the terminal. Input characters will not be stripped to seven bits if -istrip is used.

  2. The stty command sets Control-H, the Backspace key, to erase.

  3. Any line beginning with # is a comment. It is not an executable statement.

  4. If the current terminal window (tty) is the console (linux), the next line is executed; otherwise, program control goes to the last endif.

  5. This line is echoed to the screen, and if the user does not press Control-C to kill the process, the program will sleep (pause) for five seconds, and then the X windows program will start.

  6. The startx program launches X windows.

  7. The endif marks the end of the innermost if construct.

  8. The autologout variable is set to 60 so that after 60 minutes of inactivity, the user will automatically be logged out (from the login shell).

13.2.2 The Search Path

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.

Example 13.5
# 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

  1. The search path is set for tcsh. It consists of a space-separated list of directories searched from left to right by tcsh when a command is entered at the command line. The search path is local to the current shell. (See "Setting Local Variables" on page 905.)

  2. The value of the path variable is displayed

  3. The value of the environment variable, PATH, is displayed. It is a colon-separated list of the same directories as listed in the path variable, and is passed to other programs or applications invoked from the current shell. (Bash, sh, and ksh set the path as a colon-separated list.)

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 

13.2.3 The Shell Prompts

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.

Table 13.1. Prompt Strings
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.

Example 13.6
1   > set prompt = '[ %n@%m %c]# ' 2   [ ellie@homebound ~]#  cd .. 3   [ ellie@homebound /home]#  cd .. 

EXPLANATION

  1. The primary prompt is assigned the user's login name (%n), followed by the hostname (%m), a space, and the current working directory. The string is enclosed in square brackets, followed by a #.

  2. The new prompt is displayed. The ~ appearing in the prompt represents the user's home directory. The cd command changes directory to the parent directory.

  3. The new prompt indicates the current working directory, /home. In this way the user always know what directory he is in.

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.

Example 13.7
1   > foreach pal (joe tom ann) 2   foreach? echo Hi $pal 3   foreach? end     Hi joe     Hi tom     Hi ann 4   > 

EXPLANATION

  1. This is an example of online scripting. Because the TC shell is expecting further input after the foreach loop is entered, the secondary prompt appears. The foreach loop processes each word in the parenthesized list.

  2. The first time in the loop, joe is assigned to the variable pal, and the string Hi joe is displayed. The next time through the loop, tom is assigned to the variable pal, and so on.

  3. The end statement marks the end of the loop. When all of the items in the parenthesized list have been processed, the loop ends and the primary prompt is displayed.

  4. The primary prompt is displayed.

Example 13.8
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

  1. The secondary prompt, prompt2, is reset to the formatted string where %R is the name of the conditional or looping construct entered in line 2 at the primary prompt. The two percent signs will evaluate to one percent sign.

  2. The foreach command has been started. This is a looping construct that must end with the keyword end. The secondary prompt will continue to appear until the loop is properly terminated.

  3. The secondary prompt is foreach %.

  4. After the end keyword is typed, the loop executes.

  5. The primary prompt reappears, awaiting user input.

13.2.4 The Command Line

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.

Example 13.9
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

  1. The grep program searches for the pattern ellie in the /etc/passwd file and is successful. The line from /etc/passwd is displayed.

  2. The status variable is set to the exit value of the grep command; 0 indicates success. The ? variable also holds the exit status. This is also the variable used by the bash and ksh shells for checking exit status. (It is not used by csh.)

  3. The grep program cannot find user nicky in the /etc/passwd file.

  4. The grep program cannot find the pattern, so it returns an exit status of 1.

  5. The grep fails because the file /etc/passsswd cannot be opened.

  6. Grep cannot find the file, so it returns an exit status of 2.

  7. The special tcsh variable printexitvalue is set. It will automatically print the exit value of any command that exits with a nonzero value.

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.

Example 13.10
> ls; pwd; cal 2001 

EXPLANATION

The 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.

Example 13.11
1   > ( ls ; pwd; cal 2001 ) > outputfile 2   > pwd; ( cd / ; pwd ) ; pwd     /home/jody/ellie     /     /home/jody/ellie 

EXPLANATION

  1. The output of each of the commands is sent to the file called outputfile. Without the parentheses, the output of the first two commands would go to the screen, and only the output of the cal command would be redirected to the output file.

  2. The pwd command displays the present working directory. The parentheses cause the commands enclosed within them to be processed by a subshell. The cd command is built into the shell. While in the subshell, the directory is changed to root and the present working directory is displayed. When out of the subshell, the present working directory of the original shell is displayed.

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.

Example 13.12
> grep '^tom:' /etc/passwd && mail tom < letter 

EXPLANATION

If 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.

Example 13.13
> grep '^tom:' /etc/passwd || echo "tom is not a user here." 

EXPLANATION

If 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.

Example 13.14
1   > man tcsh | lpr & 2   [1] 4664 3   > 

EXPLANATION

  1. The output from the man pages for the tcsh program is piped to the printer. The ampersand at the end of the command line puts the job in the background.

  2. There are two numbers that appear on the screen: the number in square brackets indicates that this is the first job to be placed in the background; the second number is the PID of this job.

  3. The shell prompt appears immediately. While your program is running in the background, the shell is prompting you for another command in the foreground.

13.3 Command Line Shortcuts

13.3.1 History

The history mechanism is built into the TC shell. It keeps in memory a sequentially numbered list of the commands, called events, that you have typed at the command line. 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.

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

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

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

EXPLANATION

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

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

Example 13.16
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

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

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

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

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

Example 13.17
1   set savehist 2   set savehist = 1000 3   set savehist = 1000 merge 

EXPLANATION

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

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

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

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

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

EXPLANATION

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

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

Example 13.19
1   > history -h        # Print without line numbers     ls     vi file1     df     ps -eaf     history     more /etc/passwd     cd     echo $USER     set     history -n 2   > history -c 

EXPLANATION

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

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

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

EXPLANATION

The history list is displayed in reverse order.

Example 13.21
> history 5       # Print the last 5 events on the history list 7  echo $USER 8  cd 9  set 10 history -n 11 history 5 

EXPLANATION

The last five commands on the history list are executed.

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

  1. The Arrow Keys

    To access commands from the history list, you can use the arrow keys on the keyboard to move up and down through the history list, and from left to right. You can edit any of the lines in the history list by using the standard keys for deleting, backspacing, etc. As soon as you have edited the line, pressing the carriage return (Enter key) will cause the command line to be reexecute. You can also use standard emacs or vi commands to edit the history list. (See 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.)

Table 13.3. The Arrow Keys
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.
  1. 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.

Example 13.22
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. The UNIX date command is executed at the command line. The history list is updated. This is the last command on the list.

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

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

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

  5. The command is mistyped.

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

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

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

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

Example 13.23
1   > cat file1 file2 file3         <Contents of files displayed here>     > vi !:1     vi file1 2   > cat file1 file2 file3     <Contents of file, file2, and file3 are displayed here>     > ls !:2     ls file2     file2 3   > cat file1 file2 file3     > ls  !:3     ls file3     file3 4   > echo a b c     a b c     > echo !$     echo c     c 5   > echo a b c     a b c     > echo !^     echo a     a 6   > echo a b c     a b c     > echo !*     echo a b c     a b c 7   > !!:p     echo a b c 

EXPLANATION

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

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

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

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

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

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

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

 

Table 13.4. Substitution and History
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.

13.3.2 The Built-In Command Line Editors

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

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

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

Table 13.6. emacs Commands
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.

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

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

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.

Table 13.7. Key Binding Characters
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.
Example 13.26
1   > bindkey ^L     "^L"      ->     clear-screen 2   > bindkey ^C     "^C"      ->     tty-sigintr 3   > bindkey "j"     "j"       ->     self-insert-command 4   > bindkey -v 5   > bindkey -a "j"     "j"       ->     down-history 

EXPLANATION

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

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

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

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

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

Example 13.27
1   > bindkey "^T" clear-screen 2   > bindkey "^T"     "^T"      ->     clear-screen 3   > bindkey -a "^T"     "^T"      ->     undefined-key 4   > bindkey -a  [Control-v Control t] clear-screen          Press keys one after the other 5   > bindkey -a [Control-v Control t]     "^T"       ->     clear-screen 6   > bindkey -s '\ehi'  'Hello to you!\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

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

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

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

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

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

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

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

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

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

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

 

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

13.3.3 Command, Filename, and Variable Completion

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

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

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

Example 13.28
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

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

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

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

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

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

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

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

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

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

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

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

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

Example 13.29
1   > ls     baby       box.gif   file2    prog.c     baby.gif   file1     file3    prog.o 2   > set fignore = (.o .gif ) 3   > echo ba[tab]    # Completes baby but ignores baby.gif     baby 4   > echo box[tab].gif    # fignore is ignored if only one completion     box.gif                # is possible 5   > vi prog[tab]         # Expands to prog.c     Starts vi with prog.c as its argument 

EXPLANATION

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

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

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

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

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

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

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

Example 13.30
1   > set complete=enchance 2   > ls g..[tab]   expands to gawk-3.0.3     gawk-3.0.3 3   > ls GAW[tab]   expands to gawk-3.0.3     gawk-3.0.3 

EXPLANATION

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

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

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

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

Types of Completions. There three types of completions: p, n, and c. A p-type completion is position-dependent. It rules the way a completion is performed based on the position of a word in the command line, where position 0 is the command, position 1 is the first argument, position 2 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.

Example 13.31
# p-type completions (positional completion) 1   > complete     alias     'p/1/a/'     cd        'p/1/d/'     ftp       'p/1/( owl ftp.funet.fi prep.ai.mit.edu )'     man       'p/*/c/' 2   > complete  vi  'p/*/t/' 3   > complete vi     vi  'p/*/t/' 4   > set autolist 5   > man fin[tab]    # Completes command names     find     find2perl   findaffix  findsmb  finger 6   > vi b[tab]       # Completes only filenames, not directories     bashtest binded bindings bindit 7   > vi na[tab]mes 8   > cd sh[tab]ellsolutions/ 9   > set hosts = ( netcom.com 192.100.1.10 192.0.0.200 ) 10  > complete telnet 'p/1/$hosts/' 11  > telnet net[tab]com.com     telnet netcom.com 12  > alias m[tab]   # Completes alias names     mc mroe mv 13  > ftp prep[tab] 

EXPLANATION

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

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

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

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

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

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

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

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

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

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

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

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

 

Table 13.9. Completion Word Types
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.

Example 13.32
# c-type completions 1   > complete     stty     'c/-/(raw xcase noflsh)/'     bash     'c/-no/(profile rc braceexpansion)/'     find     'c/-/(user name type exec)/'     man      'c/perl/(delta faq toc data modlib locale)/' 2   > stty -r[tab]aw     stty -raw 3   > bash -nop[tab]rofile     bash -noprofile 4   > find / -n[tab]ame .tcshrc -p[tab]rint     find / -name .tcshrc -print 5   > man perlde[tab]lta     man perldelta 6   > uncomplete stty     > complete     bash     'c/-no/(profile rc braceexpansion)/'     find     'c/-/(user name type exec)/'     man      'c/perl/(delta faq toc data modlib locale)/' 7   > uncomplete * 

EXPLANATION

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

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

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

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

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

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

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

An n-type completion matches the first word and completes the second one.

Example 13.33
# n-type completions (next word completion) 1   > complete     rm   'n/-r/d/'     find 'n/-exec/c/' 2   > ls -ld testing     drwxr-sr-x  2  ellie  root   1024 Aug 29 11:02 testing 3   > rm -r te[tab]sting 

EXPLANATION

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

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

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

13.3.4 Manipulating the Directory Stack

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

Table 13.10. Directory Stack Variables
pushdtohome If set, pushd without arguments is same as pushd ~ or cd.
dunique Before pushing a directory onto the stack, removes any directories with the same name.
pushdsilent Doesn't print the directory stack when pushd is executed.
deextract If set, pushd +n extracts the 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.
Example 13.34
1   > pwd     /home/ellie     > pushd ..     /home ~     > pwd     /home 2   > pushd       # Swap the two top directories on the stack     ~ /home     > pwd     /home/ellie

graphics/13prfig01.gif

EXPLANATION

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

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

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

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

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

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

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

13.3.5 Spelling Correction

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

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

Example 13.35
1   > fimger[Alt-s]    # Replaces fimger with finger 2   > set correct=all 3   > dite     CORRECT>date (y|n|e|a)? yes     Wed Aug 11 19:26:27 PDT 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

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

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

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

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

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

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

 

Table 13.11. The correct Variable Arguments
Argument What It Does
cmd Spell-corrects commands.
complete Completes commands.
all Spell-corrects entire command line.

13.3.6 Aliases

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

The TC shell has some additional preset aliases, which remain undefined until you define them. They are: beepcmd\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.

Example 13.36
> alias apache  $HOME/apache/httpd -f $HOME/apache/conf/httpd.conf co      compress cp      cp -i ls1     enscript -B -r -Porange -f Courier8 !* & mailq   /usr/lib/sendmail -bp mc      setenv MC '/usr/bin/mc -P !*'; cd $MC; unsetenv MC 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) 

EXPLANATION

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

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

FORMAT

alias alias aliasname command alias aliasname 'command command(s)' unalias aliasname 
Example 13.37
1   > alias m more 2   > alias mroe more 3   > alias lf ls-F 4   > alias cd ' cd \!*; set prompt = "%/ > "' 5   > cd .. 6   /home/jody >  cd /         # New prompt displayed     / > 7   > set tperiod = 60     > alias periodic 'echo You have worked an hour, nonstop' 8   > alias Usage ' echo "Error: \!* " ; exit 1' 

EXPLANATION

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

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

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

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

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

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

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

  8. This alias is useful in scripts to produce a diagnostic message and to then exit the script.

[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.

Example 13.38
1   > unalias mroe 2   > \cd .. 

EXPLANATION

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

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

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

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

EXPLANATION

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

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

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

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

13.4 Job Control

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.

Table 13.12. Job Control Commands
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.

13.4.1 Background Jobs

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.

Example 13.40
1   > find . -name core -exec rm {} \; & 2   [1]  543 3   > 

EXPLANATION

  1. The find command runs in the background. (Without the -print option, the find command does not send any output to the screen).[a]

  2. The number in square brackets indicates this is the first job to be run in the background and the PID for this process is 543.

  3. The prompt returns immediately. The shell waits for user input.

[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.

Example 13.41
(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

  1. The jobs command lists the currently active jobs.

  2. The notation [1] is the number of the first job; the plus sign indicates that the job is not the most recent job to be placed in the background; the dash indicates that this is the most recent job put in the background; Suspended means that this job was stopped with ^Z and is not currently active.

  3. The -l option (long listing) displays the number of the job as well as the PID of the job. The notation [2] is the number of the second job, in this case, the last job placed in the background. The dash indicates that this is the most recent job. The sleep command is running in the background.

  4. After sleep has been running for 25 seconds, the job will complete and a message saying that it has finished appears on the screen.

  5. The tcsh listjobs variable, when set to long, will print the number of a job as well as its process ID number when it is suspended. (See Table 13.25 for a list of built-in tcsh variables.).

  6. Normally the shell notifies you if a job is stopped just before it prints a prompt, but if the shell variable notify is set, the shell will notify you immediately if there is any change in the status of a background job. For example, if you are working in the vi editor, and a background job is terminated, a message will appear immediately in your vi window like this:

    [1]     Terminated                 sleep 20

13.4.2 Foreground and Background Commands

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.

Example 13.42
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

  1. The jobs command lists currently running processes, called jobs.

  2. The first job is the vi session (suspended), the second job is the cc command (running).

  3. The job numbered [1] is brought to the foreground. The number is preceded with a percent sign.

  4. The kill command is built-in. It sends the TERM (terminate) signal, by default, to a process. The argument is either the number or the PID of the process.

  5. The sleep command is stopped by pressing ^Z. The sleep command is not using the CPU and is suspended in the background.

  6. The bg command causes the last background job to start executing in the background. The sleep program will start the countdown in seconds before execution resumes. [a]

[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.

13.4.3 Scheduling Jobs

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]

FORMAT

sched sched [+]hh:mm  command sched -n 
Example 13.43
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

  1. The sched command schedules the echo command to be executed at 14:30. At that time a beep will sound (Control-G)[a] and the message will be displayed.

  2. The sched command will schedule the echo command to be executed at 5 PM.

  3. The script, logfile.sc, is scheduled to be executed 1 hour and 30 minutes from now.

  4. The sched command displays the scheduled events, in numeric order, the last one first.

  5. With a numeric argument, sched will remove the numbered job from the scheduled list. Job number 2 was removed, as shown in the output of sched.

[a] To get the ^G into the echo statement, type Ctrl-M followed by Ctrl-V, followed by Ctrl-G.

13.5 Metacharacters

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.

Table 13.13. 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.

13.5.1 Filename Substitution

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.

Table 13.14. Shell Metacharacters and Filename Substitution
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.

Example 13.44
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

  1. All the files in the current directory are listed.

  2. The echo program prints all its arguments to the screen. The asterisk (also called a splat) is a wildcard that means, match for zero or more of any characters found in a filename. All the files in the directory are matched and echoed to the screen.

  3. Filenames ending in .c are listed.

  4. All files not ending in .c are listed.

  5. Because none of the files in the directory start with z, the shell reports No match.

The Question Mark. The question mark matches exactly one character in a filename.

Example 13.45
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

  1. All the files in the current directory are listed.

  2. The question mark matches for a single-character filename. Any filenames consisting of three characters are listed.

  3. The shell looks for a filename spelled y-o-u followed by one character. There is not a file in the directory that matches these characters. The shell prints No match.

  4. The backslash preceding the question mark is used to turn off the special meaning of the question mark. Now the shell treats the question mark as a literal character.

The Square Brackets. The square brackets ([])match a filename for one character from a set or range of characters.

Example 13.46
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

  1. All the files in the current directory are listed.

  2. Filenames starting with file followed by 1, 2, or 3 are matched and listed.

  3. Filenames starting with file followed by a single character other than 1, 2, or 3 are matched and listed.

  4. Filenames starting with one letter (uppercase or lowercase), followed by one lowercase letter, and followed by a number between 1 and 5 are matched and listed.

  5. Filenames starting with file1 and followed by a 0, 1, or 2 are listed.

The Curly Braces. The curly braces ({})match for a character or string of characters in a filename that may or may not already exist.

Example 13.47
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

  1. All the files in the current directory are listed.

  2. Files starting with f and followed by the strings oo, aa, or umble are listed. Spaces inside the curly braces will cause the error message Missing }.

  3. Files starting with a followed by .c, c, or b3, b4, or b5 are listed. (The square brackets can be used inside the curly braces.)

  4. Rather than typing prog1, prog2, and prog3 and separate arguments to the mkdir command, you can use the braces to generate the new directory names.

  5. Each of the words is expanded using the braced portions either as prefixes or suffixes. It is important that the words in braces contain no whitespace.

Escaping Metacharacters and nonomatch. The backslash is used to escape the special meaning of a single character. The escaped character will represent itself.

Example 13.48
1   > got milk?     got: No match. 2   > got milk\?     got: Command not found. 3   > set nonomatch     > got milk?     got: Command not found. 

EXPLANATION

  1. The question mark is a file substitution metacharacter and evaluates to a single character. The shell looks for a file in the present working directory that contains the characters m-i-l-k, followed by a single character. If the shell cannot find the file, it reports No match. This shows you something about the order in which the shell parses the command line. The metacharacters are evaluated before the shell tries to locate the got command.

  2. The backslash protects the metacharacter from interpretation, often called escaping the metacharacter. Now the shell does not complain about a No match, but searches the path for the got command, which is not found.

  3. The built-in nonomatch variable, when set, turns off error reporting when a metacharacter is not matched. Instead of reporting No match, UNIX reports that got is not a command.

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.

Example 13.49
1   > echo ~     /home/jody/ellie 2   > cd ~/desktop/perlstuff     > pwd     /home/jody/ellie/desktop/perlstuff 3   > cd ~joe     > pwd     /home/bambi/joe 

EXPLANATION

  1. The tilde expands to the user's home directory.

  2. The tilde followed by a pathname expands to the user's home directory, followed by /desktop/perlstuff.

  3. The tilde followed by a username expands to the home directory of the user. In this example, the directory is changed to that user's home directory.

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.

Example 13.50
1   > set noglob 2   > echo * ?? [] ~     * ?? [] ~ 

EXPLANATION

  1. The variable noglob is set. It turns off the special meaning of the wildcards.

  2. The metacharacters are displayed as themselves without any interpretation.

13.6 Redirection and Pipes

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.

Table 13.15. Redirection 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.

13.6.1 Redirecting Input

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.

FORMAT

command < file 
Example 13.51
mail bob < memo 

EXPLANATION

The 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.

13.6.2 The here document

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.

FORMAT

command << MARK        ... input ... MARK 
Example 13.52
(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

  1. The cat program, without arguments, waits for keyboard input.

  2. The user types input at the keyboard.

  3. The user types ^D to terminate input to the cat program.

  4. The cat program sends its output to the screen.

Example 13.53
(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

  1. The cat program will receive input from the first DONE to the terminating DONE. The words are user-defined terminators.

  2. The question mark (?) is the secondary prompt, prompt2. It will appear until the here document is terminated with the user-defined terminator, DONE. These lines are input. When the word DONE is reached, no more input is accepted.

  3. The final terminator marks the end of input. There cannot be any spaces on either side of this word.

  4. The text between the first word DONE and the final word DONE is the output of the cat command (from here to here) and is sent to the screen. The final DONE must be against the left margin with no space or other text to the right of it.

Example 13.54
(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

  1. The shell variable name is assigned the username steve. (Normally, this example would be included in a shell script.)

  2. The variable name is expanded within the here document.

  3. The question mark (?) is the secondary prompt, prompt2. It will appear until the here document is terminated with the user-defined terminator, EOF. The mail program will receive input until the terminator EOF is reached.

  4. Command substitution is performed within the here document; that is, the command within the backquotes is executed and the output of the command is replaced within the string.

  5. The terminator EOF is reached, and input to the mail program is stopped.

13.6.3 Redirecting Output

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.)

FORMAT

command > file 
Example 13.55
cat file1 file2 > file3 

EXPLANATION

The 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.

FORMAT

command >> file 
Example 13.56
date >> outfile 

EXPLANATION

The 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.

Figure 13.3. Redirecting stdout and stderr. See Example 13.57.

graphics/13fig03.gif

Example 13.57
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. The output of the date command is sent to standard output, the screen.

  2. The output and errors are sent to outfile.

  3. Because there were no errors, the standard output is sent to outfile and the contents of the file are displayed.

Example 13.58
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

  1. To copy a file, the cp command requires both a source file and a destination file. The cp command makes a copy of file1 and puts the copy in file2. Because the cp command is given the correct syntax, nothing is displayed to the screen. The copy was successful.

  2. This time the destination file is missing and the cp command fails, sending an error to stderr, the terminal.

  3. The >& symbol is used to send both stdout and stderr to errorfile. Because the only output from the command is the error message, that is what is saved in errorfile.

  4. The contents of errorfile are displayed, showing that it contains the error message produced by the cp command.

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.

Example 13.59
(The Command Line) 1   > find . -name '*.c' >& outputfile 2   > (find . -name '*.c' > goodstuff) >& badstuff 

EXPLANATION

  1. The find command will start at the current directory, searching for all files ending in .c, and will print the output to outputfile. If an error occurs, that will also go into outputfile.

  2. The find command is enclosed within parentheses. The shell will create a subshell to handle the command. Before creating the subshell, the words outside the parentheses will be processed; that is, the badstuff file will be opened for both standard output and error. When the subshell is started, it inherits the standard input, output, and errors from its parent. The subshell then has standard input coming from the keyboard, and both standard output and standard error going to the badstuff file. Now the subshell will handle the > operator. The stdout will be assigned the file goodstuff. The output is going to goodstuff, and the errors are going to badstuff. See Figure 13.4.

    Figure 13.4. Separating stdout and stderr.

    graphics/13fig04.gif

The noclobber Variable. The special TC shell built-in variable noclobber, when set, protects you from clobbering files with redirection. See Table 13.16.

Table 13.16. The noclobber Variable
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.
Example 13.60
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

  1. The contents of filex are displayed on the screen.

  2. The output of the date command is redirected to filex. The file is truncated and its original contents overwritten.

  3. The contents of filex are displayed.

  4. The noclobber variable is set.

  5. Because filex already exists and noclobber is set, the shell reports that the file exists and will not allow it to be overwritten.

  6. The output of ls is redirected to filex because the >! operator overrides the effects of noclobber.

  7. The effects of the >! symbol were temporary. It does not turn off noclobber. It simply overrides noclobber for the command where it is implemented.

  8. Attempting to redirect and append the output of the date command to a nonexistent file causes an error message when noclobber is set.

  9. The noclobber variable is overridden with the exclamation mark attached to the >> redirection symbol.

  10. The noclobber variable is unset.

13.7 Variables

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.

Example 13.61
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

  1. Sets the tcsh built-in variable autologout variable to cause automatic logout after a specified time of inactivity has passed.

  2. Sets the built-in variable history to 50 to control the number of events displayed.

  3. Sets the user-defined variable name to George.

  4. Sets the user-defined variable machine to the output of the UNIX command. The command is in backquotes, telling the shell to perform command substitution.

  5. The $? is prepended to the variable name to test whether the variable has been set. Because the test yields a 1 (true), the variable has been set.

  6. The $? yields 0 (false). The variable has not been set.

13.7.1 Printing the Values of Variables

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.

Table 13.17. echo Options and Escape Sequences
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).

 

Table 13.18. The echo_style Variable
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.
Example 13.62
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

  1. The echo command prints its arguments to the screen. Variable substitution is performed by the shell before the echo command is executed.

  2. The echo command, by default, supports escape sequences similar to those of the C programming language and used in the SVR4 version of echo. The > is the shell prompt.

  3. With the -n option, echo displays the string without the newline.

  4. The echo_style variable is assigned the value none. Neither the BSD -n switch nor the SVR4 escape sequences are in effect.

  5. With the new echo style, the string is displayed.

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.

FORMAT

printf format [argument...] 
Example 13.63
printf "%10.2f%5d\n" 10.5  25 
Table 13.19. Format Specifiers for the printf Command
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.
Example 13.64
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

1. The GNU version of the printf command is printed. It is found in /usr/bin.

2. The argument 100 is printed as a floating point number with only two places to the right of the decimal point printing, designated by the format specification %.2f in the format string. Note that unlike C, there are no commas separating the arguments.

3,4. This time the format string specifies that three conversions will take place: the first one is %-20s (a left-justified, 20-character string), next is %-15s (a left-justified, 15-character string), and last %10.2f (a right-justified 10-character floating point number, one of those characters is the period and the last two characters are the two numbers to the right of the decimal point). Each argument is formatted in the order of the corresponding % signs, so that string Jody corresponds to first %, string Savage corresponds to the second %, and the number 28 to the last % sign. The vertical bars are used to demonstrate the width of the fields.

5. The printf command formats the string Jody and the result of the arithmetic expansion. (Refer to "Arithmetic Expansion".) Two percent (%%) signs are needed to print one percent sign (%).

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.

Example 13.65
1   > set var = net     > echo $var     net 2   > echo $varwork     varwork: Undefined variable. 3   > echo ${var}work     network 

EXPLANATION

  1. The curly braces surrounding the variable name insulate the variable from characters that follow it.

  2. A variable called varwork has not been defined. The shell prints an error message.

  3. The curly braces shield the variable from characters appended to it. $var is expanded and the string work is appended.

13.7.2 Local Variables (Visibility and Naming)

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.

Example 13.66
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

  1. The local variable round is assigned the value world.

  2. The local variable name is assigned the value Santa Claus. The double quotes keep the shell from evaluating the whitespace between Santa and Claus.

  3. The dollar sign prepended to the variable allows the shell to perform variable substitution, that is, to extract the value stored in the variable.

  4. Variable substitution is performed.

  5. A new TC shell (called a subshell) process is started.

  6. In the subshell, the variable name has not been defined. It was defined in the parent shell as a local variable.

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.

Example 13.67
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.

Example 13.68
(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 

EXPLANATION

All 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.

13.7.3 Environment Variables

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.

Example 13.69
(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

  1. The shell environment variable TERM is set to a wyse terminal.

  2. The user-defined variable PERSON is set to Joe Jr. The quotes are used to protect the space.

  3. The dollar sign ($) prepended to the variable name allows the shell to evaluate the contents of the variable, called variable substitution.

  4. The value of the environment variable PERSON is printed.

  5. The $$ variable contains the PID of the current shell. The PID is 206.

  6. The tcsh command starts a new TC shell, called a subshell.

  7. The PID of the current shell is printed. Because this is a new TC shell, it has a different PID number. The PID is 211.

  8. The environment variable PERSON was inherited by the new shell.

  9. The PERSON variable is reset to Nelly Nerd. This variable will be inherited by any shells spawned from this shell.

  10. The new value of the PERSON variable is printed.

  11. This shell is exited.

  12. The original shell is running; to attest to that, the PID 206 is printed. It is the same as it was before the subshell was started.

  13. The PERSON variable contains its original value.

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.

Example 13.70
> 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 

EXPLANATION

The 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.

13.8 Arrays

13.8.1 What Is an Array?

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.

Example 13.71
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

  1. The wordlist is enclosed within parentheses. Each word is separated by whitespace. The array is called fruit.

  2. The words in the fruit array are printed.

  3. The first element of the fruit array is printed. The subscripts start at one.

  4. The second, third, and fourth elements of the wordlist are printed. The dash allows you to specify a range.

  5. The array does not have six elements. The subscript is out of range.

  6. All elements of the fruit array are printed.

  7. The $# preceding the array is used to obtain the number of elements in the array. There are four elements in the fruit array.

  8. The $% preceding a variable or an array prints the number of characters in the word(s).

  9. Because the subscript $#fruit evaluates to the total number of elements in the array, if that value is used as an index value of the array, i.e., [$#fruit], the last element of the fruit array is printed.

  10. The second element of the array is assigned a new value. The array is printed with its replaced value, bananas.

  11. The path variable is a special TC shell array of directories used to search for commands. When you create an array, the individual elements of the path can be accessed or changed.

  12. The first element of path is printed.

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.

Table 13.20. Variable Modifiers
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.
Example 13.72
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

  1. The array is called names. It is assigned the list of words in parentheses. Each word is separated by whitespace.

  2. The array is printed.

  3. The first element of the array is printed.

  4. The array is shifted to the left by one element. The word Mark is shifted off.

  5. The array was decreased by one element after the shift.

  6. The first element of the array, after the shift, is Tom.

  7. An array called days is created. It has two elements, Monday and Tuesday.

  8. The days array is shifted one to the left.

  9. The array is printed. Tuesday is the only element left.

  10. The days array is shifted again. The array is empty.

  11. The days array is empty.

  12. This time, attempting to shift causes the shell to send an error message indicating that it cannot shift elements from an empty array.

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.

Example 13.73
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

  1. The variable name is assigned the string Thomas Ben Savage.

  2. When treated as an array, there is only one element, the entire string.

  3. The variable is enclosed in parentheses, creating an array of words, called name.

  4. The three elements of the new array are displayed.

13.9 Special Variables and Modifiers

Built into the TC shell are several variables consisting of one character. The $ preceding the character allows variable interpretation. See Table 13.21.

Table 13.21. Variables and Their Meanings
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.
Example 13.74
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

  1. The variable num is set to null. The $? preceding the variable evaluates to one if the variable has been set (either to null or some value), and to zero if the variable has not been set.

  2. The path variable is printed. It is an array of three elements. The $# preceding the variable extracts and prints the number of elements in the array.

  3. The $$ is the PID of the current process, in this case, the C shell.

  4. The $< variable accepts a word of input from the user up to the first space or newline, whichever comes first, and stores the word in the name variable. The value of the name variable is displayed.

  5. The $< variable, when quoted (double quotes) accepts a line of input from the user up to, but not including, the newline, and stores the line in the name variable. The value of the name variable is displayed.

13.9.1 Pathname Variable Modifiers

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.

Table 13.22. Pathname Modifiers
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)
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

  1. The variable pathvar is set to /home/danny/program.c.

  2. When :r is appended to the variable, the extension is removed when displayed.

  3. When :h is appended to the variable, the head of the path is displayed; that is, the last element of the path is removed.

  4. When :t is appended to the variable, the tail end of the path (the last element) is displayed.

  5. When :e is appended to the variable, the extension is displayed.

  6. The variable is set to /home/*. The asterisk expands to all the pathnames in the current directory starting in /home/.

  7. When :gt is appended to the variable, the tail end of each (global) of the path elements is displayed.

13.9.2 Upper- and Lowercase Modifiers

A special history modifier can be used to change the case of letters in a variable.

Table 13.23. Case Modifiers
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.
Example 13.76
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

  1. When :u is appended to the variable, the first letter in its value is uppercased.

  2. When :gu is appended to the variable, the first letter in each word in the list of values is uppercased.

  3. When :agu is appended to the variable, all letters in its value are uppercased.

  4. When :agl is appended to the variable, all letters in its value are lowercased.

  5. The variable is reset with all letters in its list uppercased.

13.10 Command Substitution

13.10.1 Backquotes

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.)

Example 13.77
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

  1. The UNIX command uname -n is enclosed in backquotes. When the shell encounters the backquotes, it will execute the enclosed command, uname -n, and substitute the output of the command, stardust, into the string. When the echo command prints its arguments to standard output, the name of the machine will be one of its arguments.

  2. The UNIX command pwd is executed by the shell and the output is substituted in place within the string.

  3. The local variable d is assigned the output of the date command. The output is stored as a list of words (an array).

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.

Example 13.78
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. The variable d is assigned the output of the UNIX date command. The output is stored as an array. The value of the variable is displayed.

  2. The first three elements of the array are displayed.

  3. The sixth element of the array is displayed.

  4. There are not seven elements in the array. The shell reports that the subscript is out of range.

  5. The output spans more than one line. Each newline is replaced with a space. This may not be the output you expected.

Example 13.79
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

  1. The output of the rusers command is piped to awk. If the regular expression tom is found, awk prints the first field. The first field, in this case, is the name of the machine(s) where user tom is logged on.

  2. User tom is logged on three machines. The names of the machines are displayed.

  3. The number of elements in the array is accessed by preceding the array name with $#. There are three elements in the array.

  4. The last element of the array is displayed. The number of elements in the array ($#machine) is used as a subscript.

  5. The array is displayed.

  6. The shift command shifts the array to the left. The first element of the array is dropped and the subscripts are renumbered, starting at one.

  7. The first element of the array after the shift is displayed.

  8. After the shift, the length of the array has decreased by one.

13.11 Quoting

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:

  1. 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.

  2. Single quotes will protect double quotes, and double quotes will protect single quotes.

  3. Single quotes protect all metacharacters from interpretation, with the exception of the history character (!).

  4. 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).

13.11.1 The Backslash

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.)

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

  1. The question mark is used for filename expansion. It matches for a single character. The shell is looking for a file in the current directory that is spelled y-o-u, followed by a single character. Because there is not a file by that name in the directory, the shell complains that it could not find a match with No match.

  2. The shell will not try to interpret the question mark because it is escaped with the backslash.

  3. The string is continued to the next line by escaping the newline with a backslash. (The ? is the secondary prompt, prompt2.)

  4. If the backslash is enclosed in either single or double quotes, it is printed. When not enclosed in quotes, the backslash escapes itself.

  5. When enclosed in single quotes the backslash is ignored as a quoting character; i.e., it will not protect the single apostrophe in can't. The shell sees three single quotes and reports an unmatched quote.

  6. The tcsh variable backslash_quote, if set, causes backslashes to always quote backslashes, single quotes, and double quotes.

13.11.2 Single Quotes

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).

Example 13.81
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

  1. The string is enclosed in single quotes. All characters, except the history (bang) character (!), are protected from shell interpretation.

  2. After you use the cp command, the echo program is executed. Because the !! was not protected from shell interpretation by using the backslash character, the last command on the history list is reexecuted and the cp command becomes part of the string.

  3. By quoting the history characters (!!) with backslashes, they are protected from history substitution.

  4. The quotes must be matched on the same line, or the shell reports Unmatched.

  5. If the line is to be continued, the backslash character is used to escape the newline character. The quote is matched at the end of the next line. Even though the shell ignored the newline, the echo command did not. (The ? is the secondary prompt, prompt2.)

13.11.3 Double Quotes

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.

Example 13.82
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

  1. The local variable name is assigned the value Bob. The double quotes allow the dollar sign to be used for variable substitution.

  2. The single quote is protected within double quotes.

  3. Double or single quotes will not protect the exclamation point from shell interpretation. The built-in history command is looking for the last command that began with a double quote and that event was not found.

  4. The backslash is used to protect the exclamation point.

  5. The backslash does not escape the dollar sign when used within double quotes.

13.11.4 Combining Double and Single Quotes

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.

Example 13.83
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

  1. The local variable name is assigned Tom.

  2. The single quote in the word can't is protected when enclosed within double quotes. The shell would try to perform variable substitution if the dollar sign in $5.00 were within double quotes. Therefore, the string $5.00 is enclosed in single quotes so that the dollar sign will be a literal. The exclamation point is protected with a backslash because neither double nor single quotes can protect it from shell interpretation.

  3. The first conversational quotes are protected by the backslash. The exclamation point is also protected with a backslash. The last conversational quotes are enclosed in a set of single quotes. Single quotes will protect double quotes.

13.11.5 Steps to Successful Quoting

In a more complex command, it is often difficult to match quotes properly unless you follow the steps listed here. (See Appendix C.)

  1. 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 
  2. 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 
  3. 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:

    graphics/13infig01.gif

  4. 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.

    graphics/13prfig02.gif

13.11.6 Quoting Variables

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.

Example 13.84
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

  1. The variable is assigned the string Daniel Savage.

  2. When :q is appended to the variable, the variable is quoted. This is the same as enclosing the variable in double quotes.

  3. The double quotes surrounding the variable $name allow variable substitution to take place, but protect any whitespace characters. Without the double quotes, the grep program will search for Daniel in a file called Savage and a file called database.

  4. The variable food is assigned the string apple pie.

  5. The variable dessert is assigned an array (wordlist) consisting of apple pie and ice cream.

  6. The number of elements in the dessert array is three. When the food variable was expanded, the quotes were removed. There are three elements, apple, pie, and ice cream.

  7. The first element of the array is printed. The variable expands to separated words if not quoted.

  8. The second element of the array is printed.

  9. Since "ice cream" is quoted, it is treated as one word.

  10. The dessert array is assigned apple pie and ice cream. The :q can be used to quote the variable in the same way double quotes quote the variable; i.e., $food:q is the same as "$food".

  11. The array consists of two strings, apple pie and ice cream.

  12. The first element of the array, apple pie, is printed.

  13. The second element of the array, ice cream, is printed.

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.

Example 13.85
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

  1. The variable things is assigned a string. Each string contains a wildcard. The number of elements in the variable is one, one string.

  2. When attempting to create an array out of the string things, the TC shell tries to expand the wildcard characters to perform filename substitution within things and produces a No match.

  3. The :x extension prevents the shell from expanding the wildcards in the things variable.

  4. The array newthings consists of three elements.

  5. To print the elements of the array, they must be quoted or, again, the shell will try to expand the wildcards.

  6. The :q quotes the variable just as though the variable were surrounded by double quotes. The grep program will print any lines containing the pattern a?? in file filex.

13.12 Built-In Commands

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:

Example 13.86
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.

Table 13.24. Built-In Commands and Their Meanings
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.

-p, prints the final directory stack, just like dirs.

-l, -n, and -v flags have the same effect on cd as on dirs, and they imply -p.

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.

(+) -n, entries are wrapped before they reach the edge of the screen.

(+) -v, entries are printed one per line preceded by their stack postions.

-S, the second form saves the directory stack to filename as a series of cd and pushd commands.

-L, the shell source's filename, which is presumably a directory stack file saved.

 

In either case, dirsfile is used if filename is not given and ~/.cshdirs is used if dirsfile is unset.

With -c, form clears the directory stack.

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.

13.12.1 Special Aliases

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.

13.12.2 Special Built-In Shell Variables

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.)

Table 13.25. Special Shell Variables[23]
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.
mail 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.

Table 13.26. Shell Command Line Switches[*]
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.

TC SHELL LAB EXERCISES

Lab 57: Getting Started

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:

  1. Create three of your own aliases.

  2. Reset your prompt with the host machine name, time, and username.

  3. Set the following variables and put a comment after each variable explaining what it does.

7:

Type the following:

source .tcshrc 

What does the source command do?

8:

Edit your .login file as follows:

  1. Welcome the user.

  2. Add your home directory to the path if it is not there.

  3. Source the login file.

9:

What is the difference between path and PATH?

Lab 58: History

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:

  1. ls -a

  2. date '+%T'

  3. cal 2000

  4. cat /etc/passwd

  5. cd

5:

Type history. What is the output?

  1. How do you reexecute the last command?

  2. Now type echo a b c.

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.

Lab 59: Shell Metacharacters

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. List all files starting with a.

  2. List all files ending in at least one digit.

  3. List all files not starting with an a or A.

  4. List all files ending in a period, followed by a digit.

  5. List all files containing just two letters.

  6. List three-character files where all letters are uppercase.

  7. List files ending in 11 or 12.

  8. List files ending in x or y.

  9. List all files ending in a digit, an uppercase letter, or a lowercase letter.

  10. List all files containing a b.

  11. Remove two-character files starting with a.

Lab 60: Redirection

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:

  1. Redirect the output of the ls command to a file called lsfile?

  2. Redirect and append the output of the date command to lsfile?

  3. Redirect the output of the who command to lsfile? What happened?

4:

What happens when you type cp all by itself?

  1. How do you save the error message from the above example to a file?

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.

Lab 61: Variables and Arrays

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.

  1. Print the array.

  2. Print the last element of the array.

  3. Print the number of elements in the array.

  4. Remove the first element from the array.

  5. If you store an item that isn't fruit in the array, is it OK?

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


UNIX Shells by Example
UNIX Shells by Example, 3rd Edition
ISBN: 013066538X
EAN: 2147483647
Year: 2001
Pages: 18
Authors: Ellie Quigley

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net