UNIX in a Nutshell: System V Edition

UNIX in a Nutshell: System V EditionSearch this book
Previous: 4.2 SyntaxChapter 4
The Bourne Shell and Korn Shell
Next: 4.4 Arithmetic Expressions
 

4.3 Variables

This section describes the following:

4.3.1 Variable Substitution

ksh93 provides structured variables, such as pos.x and pos.y. To create either one, pos must already exist, and braces must be used to retrieve their values. Names beginning with .sh are reserved for use by ksh.

No spaces should be used in the following expressions. The colon (:) is optional; if it's included, var must be nonnull as well as set.

var=value ...

Set each variable var to a value.

${var}

Use value of var; braces are optional if var is separated from the following text. They are required in ksh93 if a variable name contains periods.

${var:-value}

Use var if set; otherwise, use value.

${var:=value}

Use var if set; otherwise, use value and assign value to var.

${var:?value}

Use var if set; otherwise, print value and exit (if not interactive). If value isn't supplied, print the phrase "parameter null or not set."

${var:+value}

Use value if var is set; otherwise, use nothing.

In the Korn shell:

${#var}

Use the length of var.

${#*}

Use the number of positional parameters.

${#@}

${var#pattern}

Use value of var after removing pattern from the left. Remove the shortest matching piece.

${var##pattern}

Same as #pattern, but remove the longest matching piece.

${var%pattern}

Use value of var after removing pattern from the right. Remove the shortest matching piece.

${var%%pattern}

Same as %pattern, but remove the longest matching piece.

In ksh93:

${!prefix*}

List of variables whose names begin with prefix.

${!prefix@}

${var:pos}

Starting at position pos (0-based) in variable var, extract len characters, or rest of string if no len. pos and len may be arithmetic expressions.

${var:pos:len}

${var/pat/repl}

Use value of var, with first match of pat replaced with repl.

${var/pat}

Use value of var, with first match of pat deleted.

${var//pat/repl}

Use value of var, with every match of pat replaced with repl.

${var/#pat/repl}

Use value of var, with match of pat replaced with repl. Match must occur at beginning of the value.

${var/%pat/repl}

Use value of var, with match of pat replaced with repl. Match must occur at end of the value.

In ksh93, indirect variables allow you to "alias" one variable name to affect the value of another. This is accomplished using typeset -n:

$ greet="hello, world"			Create initial variable
$ typeset -n friendly_message=greet		Set up alias
$ echo $friendly_message			Access old value through new name
hello, world
$ friendly_message="don't panic"		Change the value
$ echo $greet				Old variable is changed
don't panic

4.3.1.1 Examples

$ u=up d=down blank=		Assign values to three variables (last is null)
$ echo ${u}root			Braces are needed here
uproot
$ echo ${u-$d}                         Display value of u or d; since u is set, it's printed
up
$ echo ${tmp-`date`}	          If tmp is not set, the date command is executed
Thu Feb  4 15:03:46 EST 1993
$ echo ${blank="no data"}		blank is set, so it is printed (a blank line)
$ echo ${blank:="no data"}		blank is set but null, so the string is printed
no data	
$ echo $blank			blank now has a new value 
no data

4.3.1.2 Korn shell example

tail='${PWD##*/}'	Take the current directory name and remove the longest character string ending
		with /, which removes the leading pathname and leaves the tail

4.3.2 Built-in Shell Variables

Built-in variables are automatically set by the shell and are typically used inside shell scripts. Built-in variables can make use of the variable substitution patterns shown previously. Note that the $ is not actually part of the variable name, although the variable is always referenced this way.

$#

Number of command-line arguments.

$-

Options currently in effect (arguments supplied to sh or to set).

$?

Exit value of last executed command.

$$

Process number of current process.

$!

Process number of last background command.

$0

First word; that is, command name. This will have the full path name if it was found via a PATH search.

$n

Individual arguments on command line (positional parameters). The Bourne shell allows only nine parameters to be referenced directly (n = 1-9); the Korn shell allows n to be greater than 9 if specified as ${n}.

$*, $@

All arguments on command line ($1 $2 ...).

"$*"

All arguments on command line as one string ("$1 $2...").

"$@"

All arguments on command line, individually quoted ("$1" "$2" ...).

The Korn shell automatically sets these additional variables:

$_

Temporary variable; initialized to pathname of script or program being executed. Later, stores the last argument of previous command. Also stores name of matching MAIL file during mail checks.

LINENO

Current line number within the script or function.

OLDPWD

Previous working directory (set by cd).

OPTARG

Name of last option processed by getopts.

OPTIND

Numerical index of OPTARG.

PPID

Process number of this shell's parent.

PWD

Current working directory (set by cd).

RANDOM[=n]

Generate a new random number with each reference; start with integer n, if given.

REPLY

Default reply, used by select and read.

SECONDS[=n]

Number of seconds since the shell was started, or, if n is given, number of seconds + n since the shell started.

ksh93 automatically sets these additional variables. Variables whose names contain "." must be enclosed in braces when referenced, e.g., ${.sh.edchar}.

HISTCMD

The history number of the current command.

.sh.edchar

The character(s) entered when processing a KEYBD trap. Changing it replaces the characters that caused the trap.

.sh.edcol

The position of the cursor in the most recent KEYBD trap.

.sh.edmode

Will be equal to ESCAPE if in a KEYBD trap in vi mode, otherwise empty.

.sh.edtext

The characters in the input buffer during a KEYBD trap.

.sh.name

The name of the variable running a discipline function.

.sh.subscript

The subscript of the variable running a discipline function.

.sh.value

The value of the variable inside the set and get discipline functions.

.sh.version

The version of ksh93.

4.3.3 Other Shell Variables

The following variables are not automatically set by the shell. They are typically used in your .profile file, where you can define them to suit your needs. Variables can be assigned values by issuing commands of the form:

variable=value

This list includes the type of value expected when defining these variables. Those that are specific to the Korn shell are marked as (K). Those that are specific to ksh93 are marked (K93).

CDPATH=dirs

Directories searched by cd; allows shortcuts in changing directories; unset by default.

COLUMNS=n

(K) Screen's column width; used in line edit modes and select lists.

EDITOR=file

(K) Pathname of line edit mode to turn on (can end in emacs or vi); used when VISUAL is not set.

ENV=file

(K) Name of script that gets executed at startup; useful for storing alias and function definitions. For example, ENV=$HOME/.kshrc (like C shell's .cshrc).

FCEDIT=file

(K) Editor used by fc command (default is /bin/ed). Obsoleted in ksh93 by HISTEDIT.

FIGNORE=pattern

(K93) Pattern describing the set of filenames to ignore during pattern matching.

FPATH=dirs

(K) Directories to search for function definitions; undefined functions are set via typeset -fu; FPATH is searched when these functions are first referenced. (ksh93 also searches PATH.)

HISTEDIT=file

(K93) Editor used by hist command, if set. Overrides the setting of FCEDIT.

HISTFILE=file

(K) File in which to store command history (must be set before ksh is started); default is $HOME/.sh_history.

HISTSIZE=n

(K) Number of history commands available (must be set before ksh is started); default is 128.

HOME=dir

Home directory; set by login (from /etc/passwd file).

IFS='chars'

Input field separators; default is space, tab, and newline.

LANG=dir

Directory to use for certain language-dependent programs.

LC_ALL=locale

(K93) Current locale; overrides LANG and the other LC_* variables.

LC_COLLATE=locale

(K93) Locale to use for character collation (sorting order).

LC_CTYPE=locale

(K93) Locale to use for character class functions. (See the earlier section "Filename Metacharacters.")

LC_NUMERIC=locale

(K93) Locale to use for the decimal-point character.

LINES=n

(K) Screen's height; used for select lists.

MAIL=file

Default file in which to receive mail; set by login.

MAILCHECK=n

Number of seconds between mail checks; default is 600 (10 minutes).

MAILPATH=files

One or more files, delimited by a colon, in which to receive mail. Along with each file, you may supply an optional message that the shell prints when the file increases in size. Messages are separated from the file name by a separator character. The Korn shell separator is ?, and the default message is You have mail in $_. $_ is replaced with the name of the file. The Bourne shell separator is %, and the default message is You have mail. For example, for ksh, you might have:

MAILPATH="$MAIL?Ring! Candygram!:/etc/motd?New Login Message"

PATH=dirlist

One or more pathnames, delimited by colons, in which to search for commands to execute. Default for SVR4 is /bin:/usr/bin. On Solaris, the default is /usr/bin:. However, the standard start-up scripts change it to:

/usr/bin:/usr/ucb:/etc:.
ksh93: PATH is also searched for function definitions for undefined functions.

PS1=string

Primary prompt string; default is $.

PS2=string

Secondary prompt (used in multiline commands); default is >.

PS3=string

(K) Prompt string in select loops; default is #?.

PS4=string

(K) Prompt string for execution trace (ksh -x or set -x); default is +.

SHACCT=file

"Shell account"; file in which to log executed shell scripts. Not in Korn shell.

SHELL=file

Name of default shell (e.g., /bin/sh).

TERM=string

Terminal type.

TMOUT=n

(K) If no command is typed after n seconds, exit the shell.

VISUAL=path

(K) Same as EDITOR, but VISUAL is checked first.

4.3.4 Arrays

The Korn shell supports one-dimensional arrays of up to 1024 elements. The first element is numbered 0. An array name can be initialized as follows:

set -A name value0 value1 ...

where the specified values become elements of name. Declaring arrays is not required, however. Any valid reference to a subscripted variable can create an array.

When referencing arrays, use the ${ ... } syntax. This isn't needed when referencing arrays inside (( )) (the form of let that does automatic quoting). Note that [ and ] are typed literally (i.e., they don't stand for optional syntax).

${name[i]}

Use element i of array name. i can be any arithmetic expression as described under let. The expression must return a value between 0 and 1023.

${name}

Use element 0 of array name.

${name[*]}

Use all elements of array name.

${name[@]}

${#name[*]}

Use the number of elements in array name.

${#name[@]}

ksh93 provides associative arrays, where the indices are strings instead of numbers (as in awk). In this case, [ and ] act like double quotes. Associative arrays are created with typeset -A. A special syntax allows assigning to multiple elements at once:

data=([joe]=30 [mary]=25)

The values would be retrieved as ${data[joe]} and ${data[mary]}.

4.3.5 Discipline Functions (ksh93 only)

Along with structured variables, ksh93 introduces discipline functions. These are special functions that are called whenever a variable's value is accessed or changed. For a shell variable named x, you can define the following functions:

x.get

Called when x's value is retrieved ($x).

x.set

Called when x's value is changed (x=2).

x.unset

Called when x is unset (unset x).

Within the discipline functions, special variables provide information about the variable being changed:

.sh.name

The name of the variable being changed.

.sh.subscript

The subscript of the array element being changed.

.sh.value

The value of the variable being assigned or returned. Changing it within the discipline function changes the value that is actually assigned or returned.


Previous: 4.2 SyntaxUNIX in a Nutshell: System V EditionNext: 4.4 Arithmetic Expressions
4.2 SyntaxBook Index4.4 Arithmetic Expressions

The UNIX CD Bookshelf NavigationThe UNIX CD BookshelfUNIX Power ToolsUNIX in a NutshellLearning the vi Editorsed & awkLearning the Korn ShellLearning the UNIX Operating System