10.2. The TC Shell Environment

10.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 10.2.
# /etc/csh.cshrc

# System wide 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 1000000 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 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 1000 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. Thenonomatch 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 10.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). Linux 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 10.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).

10.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 tcshell than it is in thebash and Korn shells. Each element is separated by white space in the tcshell, but separated by colons in the other shells.

[4] Do not confuse the search path variable with the cdpath variable set in the .cshrc file.

The tcshell 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 10.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.)

  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:

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.

[5] On machines without vfork(2), prints the number and size of hash buckets.

							> 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
						

10.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 10.1.

Table 10.1. Prompt Strings
%/ 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 10.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 10.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. The user joe is sent the contents of memo in the mail. Then 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 10.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.

10.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 white space (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 Linux 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]

[6] The length of the command line can be at least 256 characters.

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 10.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 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 10.10.
> ls; pwd; cal 2000
						

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 10.11.
1  > ( ls ; pwd; cal 2000 ) > 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-in to 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 10.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 10.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 10.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.

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

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