10.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 (tcsh).

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 10.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 back quotes, telling the shell to perform command substitution.

  5. The $? is prepended to the variable name to test whether or not 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.

10.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 10.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 10.18. See the manual page for echo.

Table 10.17. echo Options and Escape Sequences
Option Meaning
-n Suppresses newline at the end of a line of output
Escape Sequence
a Alert (bell)
 Backspace
c Print the line without a newline
f Form feed
Newline
Return
Tab
v Vertical tab
\ Backslash
nn The character whose ASCII code is nnn (octal)

Table 10.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 10.62.
1   > echo The username is $LOGNAME.
							The username is ellie.

2   > echo "		Hello therec"
							Hello there>

3   >  echo -n "Hello there"
							Hello there$

4   >  set echo_style=none

5   > echo  "		Hello therec"
    -n 		Hello therec

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 10.63.
printf "%10.2f%5d
" 10.5  25

Table 10.19. Format Specifiers for the printf Command
Format Specifier Value
" Double quote
NNN An octal character in which NNN represents 0 to 3 digits
\ Backslash
a Alert or beep
 Backspace
c Produce no further output
f Form feed
Newline
Carriage return
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 10.64.
1   >  printf --version
							printf (GNU sh-utils) 1.16

2   > printf "The number is %.2f
" 100
							The number is 100.00

3   > printf "%-20s%-15s%10.2f
" "Jody" "Savage" 28
							Jody                Savage              28.00

4   > printf "|%-20s|%-15s|%10.2f|
" "Jody" "Savage" 28
							|Jody                |Savage         |     28.00|

5   > printf "%s's average was %.1f%%.
" "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. 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.

  4. The printf command formats the string Jody and the result of the arithmetic expansion. (See "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 10.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.

10.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 .cshrc file, the variable will be reset every time a new C 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 10.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 white space 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 C 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 10.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 10.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.07.09 (Astron) 1998-07-07 (i386-intel-linux)
							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 unsetnoclobber, 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 Table10.24.

10.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 10.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) 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 C shell.

Example 10.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-linux
							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=linux
							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, themail command has a MAIL variable set to the location of the user's mail spooler and thexterm 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.

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

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