Section 7.3. Variables


[Page 248]

7.3. Variables

The command ksh can perform the following variable-related operations:

  • simple assignment and access

  • testing of a variable for existence

  • reading a variable from standard input

  • making a variable read-only

  • exporting of a local variable to the environment

The Korn shell also defines several local and environment variables in addition to those mentioned in Chapter 5, "The Linux Shells."

7.3.1. Creating/Assigning A Variable

The Korn shell syntax for assigning a value to a variable is:

{name=value}+ 


If a variable doesn't exist, it is implicitly created; otherwise, its previous value is overwritten. A newly created variable is always local, although it may be turned into an environment variable using a method that I'll describe shortly. To assign a value that contains spaces, surround the value by quotes. Here's an example:

$ firstName=Graham lastName=Glass age=29    ...assign vars. $ echo $firstName $lastName is $age Graham Glass is 29                          ...simple access. $ name=Graham Glass                         ...syntax error. Glass: not found $ name="Graham Glass"          ...use quotes to build strings. $ echo $name                                ...now it works. Graham Glass $ _ 


7.3.2. Accessing A Variable

ksh supports the access methods listed in Figure 7-2.

Figure 7-2. Korn shell variable access.

[Page 249]

Syntax

Action

$name

Replaced by the value of name.

${name}

Replaced by the value of name. This form is useful if the expression is immediately followed by an alphanumeric that would otherwise be interpreted as part of the variable name.

${name-word}

Replaced by the value of name if set, and word otherwise.

${name+word}

Replaced by word if name is set, and nothing otherwise.

${name=word}

Assigns word to the variable name if name is not already set, and then is replaced by the value of name.

${name?word}

Replaced by name if name is set. If name is not set, word is displayed to the standard error channel and the shell is exited. If word is omitted, then a standard error message is displayed instead.



[Page 249]

If a variable is accessed before it is assigned a value, it returns a null string.

I personally find these variable access techniques to be "hack" methods of dealing with certain conditions, and hardly ever use them. However, it's good to be able to understand code that uses them. The following examples illustrate each access method. In the first example, I used braces to append a string to the value of a variable:

$ verb=sing                  ...assign a variable. $ echo I like $verbing       ...there's no variable "verbing". I like $ echo I like ${verb}ing     ...now it works. I like singing $ _ 


Here's an example that uses command substitution to set the variable startDate to the current date if it's not already set:

$ startDate=${startDate-`date`}  ...if not set, run date. $ echo $startDate                ...look at its value. Wed May 4 06:56:51 CST 2005 $ _ 


In the next example, I set the variable x to a default value and printed its value, all at the same time:

$ echo x = ${x=10}    ...assign a default value. x = 10 $ echo $x             ...confirm the variable was set. 10 $ _ 



[Page 250]

In the following example, I displayed messages based on whether certain variables were set or not:

$ flag=1                            ...assign a variable. $ echo ${flag+'flag is set'}        ...conditional message #1. flag is set $ echo ${flag2+'flag2 is set'}      ...conditional message #2.                                     ...result is null $ _ 


In the next example, I tried to access an undefined variable called grandTotal and received an error message instead:

$ total=10                              ...assign a variable. $ value=${total?'total not set'}        ...accessed OK. $ echo $value                           ...look at its value. 10 $ value=${grandTotal?'grand total not set'}  ...not set. grandTotal: grand total not set $ _ 


In the final example, I ran a script that used the same access method as the previous example. Note that the script terminated when the access error occurred:

$ cat script.sh                   ...look at the script. value=${grandTotal?'grand total is not set'} echo done         # this line is never executed. $ script.sh                       ...run the script. script.sh: grandTotal: grand total is not set $ _ 


7.3.3. Reading a Variable from Standard Input

The read command allows you to read variables from standard input (Figure 7-3).

Figure 7-3. Description of the read shell command.

Shell Command: read { variable }+

read reads one line from standard input and then assigns successive words from the line to the specified variables. Any words that are left over are assigned to the last-named variable.



[Page 251]

If you specify just one variable, the entire line is stored in the variable. Here's an example script that prompts a user for his or her full name:

$ cat script.sh                     ...list the script. echo "Please enter your name: \c" read name                     # read just one variable. echo your name is $name       # display the variable. $ ksh script.sh                     ...run the script. Please enter your name: Graham Walker Glass your name is Graham Walker Glass    ...whole line was read. $ _ 


Here's an example that illustrates what happens when you specify more than one variable:

$ cat script.sh                     ...list the script. echo "Please enter your name: \c" read firstName lastName       # read two variables. echo your first name is $firstName echo your last name is $lastName $ ksh script.sh                     ...run the script. Please enter your name: Graham Walker Glass your first name is Graham           ...first word. your last name is Walker Glass      ...the rest. $ ksh script.sh                     ...run it again. Please enter your name: Graham your first name is Graham           ...first word. your last name is                   ...only one. $ _ 


7.3.4. Exporting Variables

The export command allows you to mark local variables for export to the environment and works as described in Figure 7-4.

Figure 7-4. Description of the export shell command.

Shell Command: export { variable }+

export marks the specified variables for export to the environment. If no variables are specified, a list of all the variables marked for export during the shell session is displayed.


Although it's not necessary, I tend to use uppercase letters to name environment variables. The env utility (Figure 7-5) allows you to modify and list environment variables.


[Page 252]

Figure 7-5. Description of the env command.

Utility: env { variable=value }* [ command ]

env assigns values to specified environment variables, and then executes an optional command using the new environment. If variables or command are not specified, a list of the current environment is displayed.


In the following example, I created a local variable called DATABASE, which I then marked for export. When I created a subshell, a copy of the environment variable was inherited:

$ export                 ...list my current exports. export TERM              ...set in my ".profile" startup file. $ DATABASE=/dbase/db     ...create a local variable. $ export DATABASE        ...mark it for export. $ export                 ...note that it's been added. export DATABASE export TERM $ env                    ...list the environment. DATABASE=/dbase/db HOME=/home/glass LOGNAME=glass PATH=:/bin:/usr/bin SHELL=/bin/ksh TERM=xterm USER=glass $ ksh                    ...create a subshell. $ echo $DATABASE         ...a copy was inherited. /dbase/db $ ^D                     ...terminate subshell. $ _ 


7.3.5. Read-Only Variables

The readonly command allows you to protect variables against modification, and works as described in Figure 7-6.

Figure 7-6. Description of the readonly shell command.

Shell Command: readonly { variable }*

readonly makes the specified variables read-only, protecting them against future modification. If no variables are specified, a list of the current read-only variables is displayed. Copies of exported variables do not inherit their read-only status.



[Page 253]

In the following example, I protected a local variable from modification. I then exported the variable and showed that its copy did not inherit the read-only status:

$ password=Shazam           ...assign a local variable. $ echo $password            ...display its value. Shazam $ readonly password         ...protect it. $ readonly                  ...list all read-only variables. readonly password $ password=Phoombah         ...try to modify it. password: is read only $ export password           ...export the variable. $ password=Phoombah         ...try to modify it. password: is read only $ ksh                       ...create a subshell. $ readonly         ...the exported password is not read-only. $ echo $password            ...its value was copied correctly. Shazam $ password=Alacazar         ...but its value may be changed. $ echo $password            ...echo its value. Alacazar $ ^D                        ...terminate the subshell. $ echo $password            ...echo original value. Shazam $ _ 


7.3.6. Predefined Local Variables

In addition to the core predefined local variables, the Korn shell defines those in Figure 7-7.

Figure 7-7. Korn shell predefined local variables.

Name

Value

$@

An individually quoted list of all the positional parameters.

$#

The number of positional parameters.

$?

The exit value of the last command.

$!

The process ID of the last background command.

$-

The current shell options assigned from the command line or by the built-in set commanddiscussed later.

$$

The process ID of this shell.



[Page 254]

Here's a small shell script that illustrates the first three variables. In this example, the C compiler (gcc) was invoked on a file that didn't exist, and therefore returned a failure exit code.

$ cat script.sh                    ...list the script. echo there are $# command line arguments: $@ gcc $1                    # compile the first argument. echo the last exit value was $?    # display exit code. $ script.sh nofile tmpfile         ...execute the script. there are 2 command line arguments: nofile tmpfile gcc: nofile: No such file or directory gcc: no input files the last exit value was 1          ...gcc errored. $ _ 


The next example illustrates how $! may be used to kill the last background process:

$ sleep 1000 &        ...bg process, ksh does not report PID. $ kill $!             ...kill it! 29455 Terminated $ echo $!             ...the process ID is still remembered. 29455 $ _ 


7.3.7. Predefined Environment Variables

In addition to the core predefined environment variables (listed in Chapter 3, "GNU Utilities for Nonprogrammers"), the Korn shell defines those in Figure 7-8.

Figure 7-8. Korn shell predefined environment variables.

Name

Value

$IFS

When the shell tokenizes a command line prior to its execution, it uses the characters in this variable as delimiters. IFS usually contains a space, a tab, and a newline character.

$PS1

This contains the value of the command-line prompt, and is $ by default. To change the command-line prompt, simply set PS1 to a new value.

$PS2

This contains the value of the secondary command line-prompt that is displayed when more input is required by the shell, and is > by default. To change the prompt, set PS2 to a new value.

$ENV

If this variable is not set, the shell searches the user's home directory for the ".profile" startup file when a new login shell is created. If this variable is set, then every new shell invocation runs the script specified by ENV.



[Page 255]

Here's a small example that illustrates the predefined environment variables used to set the command-line prompt. I set my prompt to something different by assigning a new value to PS1, and I set PS2 to a new value and illustrated an occasion where the secondary prompt is displayed.

$ PS1="ksh? "             ...set a new primary prompt. ksh? string="a long\      ...assign a string over 2 lines > string"                 ...">" is the secondary prompt. ksh? echo $string         ...look at the value of "string". a long string ksh? PS2="??? "           ...change the secondary prompt. ksh? string="a long\      ...assign a long string. ??? string"               ..."???" is new secondary prompt. ksh? echo $string         ...look at the value of "string". a long string ksh? _ 





Linux for Programmers and Users
Linux for Programmers and Users
ISBN: 0131857487
EAN: 2147483647
Year: 2007
Pages: 339

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