Linux in a NutshellLinux in a NutshellSearch this book

7.3. Variables

Preface a variable by a dollar sign ($) to reference its value. You can also optionally enclose it in braces ({ }). You can assign a value to a variable through an equals sign (=) with no whitespace on either side of it:

$ TMP=temp.file

By default, variables are seen only within the shell itself; to pass variables to other programs invoked within the shell, see the export built-in command.

If enclosed by brackets ([ ]), the variable is considered an array variable. For instance:

$ DIR_LIST[0]=src
$ DIR_LIST[1]=headers
$ ls ${DIR_LIST[1]}

The contents of headers are listed. Many substitutions and commands in this chapter handle arrays by operating on each element separately.

7.3.1. Variable Substitution

In the following substitutions, braces ({ }) are optional, except when needed to separate a variable name from following characters that would otherwise be considered part of the name.

Variable

Meaning

${var}

Value of variable var.

$0

Name of the program.

${n}

Individual arguments on command line (positional parameters); 1 ≤ n ≤ 9.

$#

Number of arguments on command line.

$*

All arguments on command line.

$@

Same as $*, but contents are split into words when the variable is enclosed in double quotes.

$$

Process number of current shell; useful as part of a filename for creating temporary files with unique names.

$?

Exit status of last command (normally 0 for success).

$!

Process number of most recently issued background command.

$-

Current execution options (see the set built-in command). By default, hB for scripts and himBH for interactive shells.

$_

Initially set to name of file invoked for this shell, then set for each command to the last word of the previous command.

Tables Table 7-16 through Table 7-18 show various types of operators that can be used with bash variables.

Table 7-16. Substitution operators

Operator

Substitution

${varname:-word}

If varname exists and isn't null, return its value; otherwise, return word.

Purpose:

Returning a default value if the variable is undefined.

Example:

${count:-0} evaluates to 0 if count is undefined.

${varname:=word}

If varname exists and isn't null, return its value; otherwise set it to word and then return its value. Positional and special parameters cannot be assigned this way.

Purpose:

Setting a variable to a default value if it is undefined.

Example:

${count:=0} sets count to 0 if it is undefined.

${varname:?message}

If varname exists and isn't null, return its value; otherwise, print varname: followed by message, and abort the current command or script (noninteractive shells only). Omitting message produces the default message "parameter null or not set."

Purpose:

Catching errors that result from variables being undefined.

Example:

{count:?"undefined"} prints "count: undefined" and exits if count is undefined.

${varname:+word}

If varname exists and isn't null, return word; otherwise, return null.

Purpose:

Testing for the existence of a variable.

Example:

${count:+1} returns 1 (which could mean true) if count is defined.

${#varname}

Return the number of characters in the value of varname.

Purpose:

Preparing for substitution or extraction of substrings.

Example:

If ${USER} currently expands to root, ${#USER} expands to 4.

Table 7-17. Pattern-matching operators

Operator

Meaning

${variable#pattern}

If the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest.

${variable##pattern}

If the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest.

${variable%pattern}

If the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest.

${variable%%pattern}

If the pattern matches the end of the variable's value, delete the longest part that matches and return the rest.

${var/pat/sub}

Return var with the first occurrence of pat replaced by sub. Can be applied to $* or $@, in which case each word is treated separately. If pat starts with # it can match only the start of var; if pat ends with % it can match only the end of var.

${var//pat/sub}

Return var with every occurrence of pat replaced by sub.

${variable:n}

Truncate the beginning of the variable and return the part starting with character number n, where the first character is 0.

${variable:n:l}

Starting with character number n, where the first character is 0, return a substring of length l from the variable.

Table 7-18. Expression evaluation

Operator

Meaning

$((arithmetic-expression))

Return the result of the expression. Arithmetic operators are described under Section 7.4.

Example:

TODAY=`date +%-d`; echo $(($TODAY+7)) stores the number of the current day in $TODAY and then prints that number plus 7 (the number of the same day next week).

[[$condition]]

Return 1 if condition is true and 0 if it is false. Conditions are described under the test built-in command.

7.3.2. Built-in Shell Variables

Built-in variables are set automatically by the shell and are typically used inside shell scripts. Built-in variables can use the variable substitution patterns shown earlier. When setting variables, you do not include dollar signs, but when referencing their values later, the dollar signs are necessary.

Tables Table 7-19 through Table 7-22 show the commonly used built-in variables in bash.

Table 7-19. Behavior-altering variables

Variable

Meaning

auto_resume

Allows a background job to be brought to the foreground simply by entering a substring of the job's command line. Values can be substring (resume if the user's string matches part of the command), exact (string must exactly match command), or another value (string must match at beginning of command).

BASH_ENV

Startup file of commands to execute, if bash is invoked to run a script.

CDPATH

Colon-separated list of directories to search for the directory passed in a cd command.

EDITOR

Pathname of your preferred text editor.

IFS

Word separator; used by shell to parse commands into their elements. The default separators are space, tab, and newline.

IGNOREEOF

If nonzero, don't allow use of a single Ctrl-D (the end-of-file or EOF character) to log off; use the exit command to log off.

PATH

Colon-separated list of directories to search for each command.

PROMPT_COMMAND

Command that bash executes before issuing a prompt for a new command.

PS1

Prompt displayed before each new command; see Section 7.5.4 for ways to introduce into the prompt dynamically changing information such as the current working directory or command history number.

PS2

Prompt displayed before a new line if a command is not finished.

PS3

Prompt displayed by select built-in command.

PS4

Prompt displayed by -x debugging (see Section 7.1) and the set built-in command).

Table 7-20. History variables

Variable

Meaning

FCEDIT

Pathname of editor to use with the fc command.

HISTCMD

History number of the current command.

HISTCONTROL

If HISTCONTROL is set to the value of ignorespace, lines beginning with a space are not entered into the history list. If set to ignoredups, lines matching the last history line are not entered. Setting it to ignoreboth enables both options.

HISTFILE

Name of history file on which the editing modes operate.

HISTFILESIZE

Maximum number of lines to store in the history file. The default is 500.

HISTSIZE

Maximum number of commands to remember in the command history. The default is 500.

Table 7-21. Mail variables

Variable

Meaning

MAIL

Name of file to check for incoming mail.

MAILCHECK

How often, in seconds, to check for new mail (default is 60 seconds).

MAILPATH

List of filenames, separated by colons (:), to check for incoming mail.

Table 7-22. Status variables

Variable

Meaning

BASH

Pathname of this instance of the shell you are running.

BASH_VERSION

Version number of the shell you are running.

COLUMNS

Number of columns your display has.

DIRSTACK

List of directories manipulated by pushd and popd commands.

EUID

Effective user ID of process running this shell, in the form of the number recognized by the system.

GROUPS

Groups to which user belongs, in the form of the numbers recognized by the system.

HOME

Name of your home (login) directory.

HOSTNAME

Host the shell is running on.

HOSTTYPE

Short name indicating the type of machine the shell is running on; for instance, i486.

LINES

The number of lines your display has.

MACHTYPE

Long string indicating the machine the shell is running on; for instance, i486-pc-linux-gnu.

OLDPWD

Previous directory before the last cd command.

OSTYPE

Short string indicating the operating system; for instance, linux-gnu.

PPID

Process ID of parent process that invoked this shell.

PWD

Current directory.

SECONDS

Number of seconds since the shell was invoked.

SHELL

Pathname of the shell you are running.

SHLVL

Depth to which running shells are nested.

TERM

The type of terminal that you are using.

UID

Real user ID of process running this shell, in the form of the number recognized by the system.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.