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 subsection describes the following:

4.3.1 Variable Substitution

No spaces should be used in the expressions below. The colon (:) is optional; if it's included, var must be non-null 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.

${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 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.

${#@}

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 longest matching piece.

${var%pattern}

Use value of var after removing pattern from the right.

${var%%pattern}

Same as %pattern, but remove longest matching piece.

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 is 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 /.
	This 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 above. 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.

$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, 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.

ERRNO

Error number of last system call that failed.

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.

4.3.3 Other Shell Variables

The variables below 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

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

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

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.

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

IFS='chars'

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

LANG=dir

Directory to use for certain language-dependent programs.

LINES=n

(K) Screen's line length; 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 10 minutes.

MAILPATH=files

One or more files, delimited by a colon, in which to receive mail. Each file is printed. The Korn shell prompt is ? and the default message is You have mail in $_. The Bourne shell prompt is % and the default message is You have mail.

PATH=dir

One or more pathnames, delimited by a colon, in which to search for commands to execute; default is /usr/bin.

PS1=string

Primary prompt string; default is $.

PS2=string

Secondary prompt (used in multi-line 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 shell environment (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, you can 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 all elements of array name.

${name}

Use element 0 of array name.

${name[*]}

Use all elements in array name.

${#name[*]}

Use the number of elements in array name.

${#name[@]}

Use the number of elements in array name.


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