There are two types of variables: local and environment. Local variables are known only to the shell in which they were created. Environment variables are available to any child processes spawned from the shell from which they were created. Some variables are created by the user and others are special shell variables.
Variable names must begin with an alpha or underscore character. The remaining characters can be alphas, decimal digits (0 to 9), or an underscore character. Any other characters mark the termination of the variable name. Names are case-sensitive. When assigning a value to a variable, do not include any white space surrounding the equal sign. To set the variable to null, follow the equal sign with a newline. The simplest format for creating a local variable is simply to assign a value to a variable in the format:
Format
variable=value
name=Tommy |
There are two built-in commands, declare and typeset, used to create variables, with options to control the way the variable is set. The typeset command (from Korn shell) is exactly the same as the declare command (bash). The bash documentation says, "The typeset command is supplied for compatibility with the Korn shell; however, it has been deprecated in favor of thedeclare built-in command." [11] So from this point on we'll use the declare built-in (even though we could just as easily have chosen to use typeset).
[11] Bash Reference Manual: http://www.delorie.com/gnu/docs/bash/bashref_56.html.
Without arguments, declare lists all set variables. Normally read-only variables cannot be reassigned or unset. If read-only variables are created with declare, they cannot be unset, but they can be reassigned. Integer-type variables can also be assigned with declare.
Format
declare variable=value
declare name=Tommy |
Option | Meaning |
---|---|
-f | Lists functions names and definitions |
-r | Makes variables read-only |
-x | Exports variable names to subshells |
-i | Makes variables integer types |
-a [a] | Treats variable as an array; i.e., assigns elements |
-F | Lists just function names |
[a] -a and -F are implemented only on versions of bash 2.x.
The scope of a variable refers to where the variable is visible within a program. For the shell, the scope of local variables is confined to the shell in which the variable is created.
When assigning a value, there can be no white space surrounding the equal sign. To set the variable to null, the equal sign is followed by a newline.[12]
[12] A variable set to a value or to null will be displayed by using the set command, but an unset variable will not.
A dollar sign is used in front of a variable to extract the value stored there.
The local function can be used to create local variables, but this is only used within functions. (See "Defining Functions" on page 360.)
Local variables can be set by simply assigning a value to a variable name, or by using the declare built-in function as shown in Example 8.55.
1 $ round=world or declare round=world $ echo $round world 2 $ name="Peter Piper" $ echo $name Peter Piper 3 $ x= $ echo $x 4 $ file.bak="$HOME/junk" bash: file.bak=/home/jody/ellie/junk: not found |
Explanation
The local variable round is assigned the value world. When the shell encounters the dollar sign preceding a variable name, it performs variable substitution. The value of the variable is displayed. (Don't confuse the prompt ($) with the $ used to perform variable substitution.)
The local variable name is assigned the value " Peter Piper. " The quotes are needed to hide the white space so that the shell will not split the string into separate words when it parses the command line. The value of the variable is displayed.
The local variable x is not assigned a value. It will be assigned null. The null value, an empty string, is displayed.
The period in the variable name is illegal. The only characters allowed in a variable name are numbers, letters, and the underscore. The shell tries to execute the string as a command.
1 $ echo $$ 1313 2 $ round=world $ echo $round world 3 $ bash Start a subshell 4 $ echo $$ 1326 5 $ echo $round 6 $ exit Exits this shell, returns to parent shell 7 $ echo $$ 1313 8 $ echo $round world |
Explanation
The value of the double dollar sign variable evaluates to the PID of the current shell. The PID of this shell is 1313.
A new bash shell is started. This is called a subshell, or child shell.
The PID of this shell is 1326. The parent shell's PID is 1313.
The local variable round is not defined in this shell. A blank line is printed.
The exit command terminates this shell and returns to the parent shell. (Control-D will also exit this shell.)
The parent shell returns. Its PID is displayed.
The value of the variable round is displayed. It is local to this shell.
A read-only variable is a special variable that cannot be redefined or unset. If, however, the declare function is used, a read-only variable can be redefined, but not unset.
1 $ name=Tom 2 $ readonly name $ echo $name Tom 3 $ unset name bash: unset: name: cannot unset: readonly variable 4 $ name=Joe bash: name: readonly variable 5 $ declare -r city='Santa Clara' 6 $ unset city bash: unset: city: cannot unset: readonly variable 7 $ declare city='San Francisco' # What happened here? $ echo $city San Francisco |
Explanation
The variable is made read-only.
A read-only variable cannot be unset.
A read-only variable cannot be redefined.
The declare built-in command assigns a read-only variable, city, the value Santa Clara. Quotes are necessary when assigning a string containing white space.
Since it is read-only, the variable cannot be unset.
When a read-only variable is created with the declare command, it cannot be unset, but it can be reassigned.
Environment variables are available to the shell in which they are created and any subshells or processes spawned from that shell. They are often called global variables to differentiate them from local variables. By convention, environment variables are capitalized. Environment variables are variables that have been exported with the export built-in command.
The shell in which a variable is created is called the parent shell. If a new shell is started from the parent shell, it is called the child shell. Environment variables are passed to any child process started from the shell where the environment variables were created. They are passed from parent to child to grandchild, etc., but not the other direction; i.e., a child process can create an environment variable, but cannot pass it back to its parent, only to its children.[13] Some of the environment variables, such as HOME, LOGNAME, PATH, and SHELL, are set before you log on by the /bin/login program. Normally, environment variables are defined and stored in the .bash_profile file in the user's home directory. See Table 8.19 for a list of environment variables.
[13] Like DNA, inheritance goes one direction only, from parent to child.
To set environment variables, the export command is used either after assigning a value or when the variable is set. The declare built-in, given the -x option, will do the same. (Do not use the dollar sign on a variable when exporting it.)
Format
export variable=value variable=value; export variable declare -x variable=value
export NAME=john PS1= `d:W:$USER> ` ; export PS1 declare -x TERM=linux |
Option | Value |
---|---|
-- | Marks the end of option processing; the remaining parameters are arguments. |
-f | Name-value pairs are treated as functions, not variables. |
-n | Converts a global (exported) variable to a local variable. The variable will not be exported to child processes. |
-p | Displays all the global variables. |
1 $ export TERM=linux or declare -x TERM=linux 2 $ NAME="John Smith" $ export NAME $ echo $NAME John Smith 3 $ echo $$ 319 pid number for parent shell 4 $ bash Start a subshell 5 $ echo $$ 340 pid number for new shell 6 $ echo $NAME John Smith 7 $ declare -x NAME="April Jenner" $ echo $NAME April Jenner 8 $ exit Exit the subshell and go back to parent shell 9 $ echo $$ 319 pid number for parent shell 10 $ echo $NAME John Smith |
Explanation
The TERM variable is assigned linux. The variable is exported at the same time. Now, processes started from this shell will inherit the variable. You can use declare -x to do the same thing.
The variable NAME is defined and exported to make it available to subshells started from the shell.
The value of this shell's PID is printed.
A new bash shell is started. The new shell is called the child. The original shell is its parent.
The PID of the new bash shell is stored in the $$ variable and its value is echoed.
The variable, set in the parent shell, was exported to this new shell and is displayed.
This bash child shell is exited.
The PID of the parent is displayed again.
The variable NAME contains its original value. Variables retain their values when exported from parent to child shell. The child cannot change the value of a variable for its parent.
Variable Name | Meaning |
---|---|
_ (underscore) | The last argument to the previous command. |
BASH | Expands to the full pathname used to invoke this instance of bash. |
BASH_ENV[*] | Same as ENV but set only in bash versions 2.0 or above. |
BASH_VERSION | Expands to the version number of this instance of bash. |
BASH_VERSINFO[*] | Version information about this version of bash if the version is 2.0 or above. |
CDPATH | The search path for the cd command. This is a colon-separated list of directories in which the shell looks for destination directories specified by the cd command. A sample value is .:~:/usr. |
COLUMNS | If set, defines the width of the edit window for shell edit modes and the select command. |
DIRSTACK[*] | The current contents of the directory stack if the bash version is 2.0 or above. |
EDITOR | Pathname for a built-in editor: emacs, gmacs, or vi. |
EUID | Expands to the effective user ID of the current user, initialized at shell startup. |
ENV | The environment file that is executed every time a new bash shell is started, including a script. Normally the filename assigned to this variable is .bashrc. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. |
FCEDIT | Default editor name for the fc command. |
FIGNORE | A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in FIGNORE is excluded from the list of matched filenames. A sample value is .o:~. |
GLOBIGNORE[*] | A list of files that will be ignored during filename expansion (called globbing). |
GROUPS[*] | An array of groups to which the current user belongs. |
HISTCMD | The history number, or index in the history list, of the current command. If HISTCMD is unset, it loses its special properties, even if it is subsequently reset. |
HISTCONTROL | If set to a value of ignorespace, lines which begin with a space character are not entered on the history list. If set to a value of ignoredups, lines matching the last history line are not entered. A value of ignoreboth combines the two options. If unset, or if set to any other value than those above, all lines read by the parser are saved on the history list. |
HISTFILE | Specifies file in which to store command history. The default value is ~/. bash_history. If unset, the command history is not saved when an interactive shell exits. |
HISTFILESIZE | The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines. The default value is 500. |
HISTSIZE | The number of commands to remember in the command history. The default value is 500. |
HOME | Home directory; used by cd when no directory is specified. |
HOSTFILE | Contains the name of a file in the same format as in /etc/hosts that should be read when the shell needs to complete a hostname. The file may be changed interactively; the next time hostname completion is attempted bash adds the contents of the new file to the already existing database. |
HOSTTYPE | Automatically set to the type of machine on which bash is executing. The default is system-dependent. |
IFS | Internal field separators, normally SPACE, TAB, and NEWLINE, used for field splitting of words resulting from command substitution, lists in loop constructs, and reading input. |
IGNOREEOF | Controls the action of the shell on receipt of an EOF character as the sole input. If set, the value is the number of consecutive EOF characters typed as the first characters on an input line before bash exits. If the variable exists but does not have a numeric value, or has no value, the default value is 10. If it does not exist, EOF signifies the end of input to the shell. This is only in effect for interactive shells. |
INPUTRC | The filename for the readline startup file, overriding the default of ~./inputrc. |
LANG[*] | Used to determine the locale category for any category not specifically selected with a variable starting with LC_. |
LC_ALL[*] | Overrides the value of LANG and any other LC_ variable. |
LC_COLLATE[*] | Determines the collation order used when sorting the results of pathname expansion and the behavior of range expressions, equivalence classes, and collating sequences when matching pathnames and patterns. |
LC_MESSSAGES[*] | Determines the locale used to translate double-quoted strings preceded by a $. |
LINENO | Each time this parameter is referenced, the shell substitutes a decimal number representing the current sequential line number (starting with 1) within a script or function. |
MACHTYPE[*] | Contains a string describing the system on which bash is executing. |
If this parameter is set to the name of a mail file and the MAILPATH parameter is not set, the shell informs the user of the arrival of mail in the specified file. | |
MAILCHECK | This parameter specifies how often (in seconds) the shell will check for the arrival of mail in the files specified by the MAILPATH or MAIL parameters. The default value is 600 seconds (10 minutes). If set to zero, the shell will check before issuing each primary prompt. |
MAILPATH | A colon-separated list of filenames. If this parameter is set, the shell informs the user of the arrival of mail in any of the specified files. Each filename can be followed by a % and a message that will be printed when the modification time changes. The default message is " you have mail. " |
MAIL__WARNING | If set, and a file that bash is checking for mail has been accessed since the last time it was checked, the message " The mail in [filename where mail is stored] has been read " is printed. |
OLDPWD | Last working directory. |
OPTARG | The value of the last option argument processed by the getopts built-in command. |
OPTERR | If set to 1, displays error messages from thegetopts built-in. |
OPTIND | The index of the next argument to be processed by the getopts built-in command. |
OSTYPE | Automatically set to a string that describes the operating system on which bash is executing. The default is system-dependent. |
PATH | The search path for commands. It is a colon-separated list of directories in which the shell looks for commands. The default path is system-dependent, and is set by the administrator who installs bash. A common value is: /usr/gnu/bin:/usr/local/bin:/usr/ucb:/bin:/usr/bin:. |
PIPESTATUS | An array containing a list of exit status values from processes in the most recently executed foreground jobs in a pipeline. |
PROMPT_COMMAND | The command assigned to this variable is executed before the primary prompt is displayed. |
PPID | Process id of the parent process. |
PS1 | Primary prompt string, by default $. |
PS2 | Secondary prompt string, by default >. |
PS3 | Selection prompt string used with the select command, by default #?. |
PS4 | Debug prompt string used when tracing is turned on, by default +. Tracing can be turned on with set -x. |
PWD | Present working directory; set by cd. |
RANDOM | Each time this parameter is referenced, a random integer is generated. The sequence of random numbers may be initialized by assigning a value to RANDOM. If RANDO is unset, it loses its special properties, even if it is subsequently reset. |
REPLY | Set when read is not supplied arguments. |
SECONDS | Each time SECONDS is referenced, the number of seconds since shell invocation is returned. If a value is assigned to SECONDS, the value returned upon subsequent references is the number of seconds since the assignment plus the value assigned. If SECONDS is unset, it loses its special properties, even if it is subsequently reset. |
SHELL | When the shell is invoked, it scans the environment for this name. The shell gives default values to PATH, PS1, PS2, MAILCHECK, and IFS. HOME and MAIL are set by login(1). |
SHELLOPTS | Contains a list of enabled shell options, such as braceexpand, hashall, monitor, etc. |
SHLVL | Incremented by one each time an instance of bashis started. |
TMOUT | Specifies number of seconds to wait for input before exiting. |
FORMAT | Used to format the output of the timereserved word on a command pipeline . |
UID | Expands to the user ID of the current user, initialized at shell startup. |
[*] only on version of bash 2.x
Both local and environment variables can be unset by using the unset command, unless the variables are set as read-only.
unset name; unset TERM
|
Explanation
The unset command removes the variable from the shell's memory.
The built-in echo command prints its arguments to standard output. Echo, with the -e option, allows the use of numerous escape sequences that control the appearance of the output. Table 8.20 lists the echo options and escape sequences.
Option | Meaning |
---|---|
-e | Allows interpretation of the escape sequences shown below |
-n | Suppresses newline at the end of a line of output |
-E [a] | Disables the interpretation of these escape characters, even on systems where they are interpreted by default (bash 2.x) |
Escape Sequence | |
a[a] | Alert (bell) |
Backspace | |
c | Prints the line without a newline |
f | Form feed |
Newline | |
Return | |
Tab | |
v | Vertical tab |
\ | Backslash |
nn | The character whose ASCII code is nnn (octal) |
[a] Not available in bash versions prior to 2.x.
When using the escape sequences, don't forget to use the -e switch!
1 $ echo The username is $LOGNAME. The username is ellie. 2 $ echo -e " Hello therec" Hello there$ 3 $ echo -n "Hello there" Hello there$ |
Explanation
The echo command prints its arguments to the screen. Variable substitution is performed by the shell before the echo command is executed.
The echo command, with the -e option, supports escape sequences similar to those of the C programming language. The $ is the shell prompt.
When the -n option is on, the line is printed without the newline. The escape sequences are not supported by this version of echo.
The Gnu version of printf [14] 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.
[14] On bash versions 2.x, printf is a built-in command.
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 you are using bash 2.x, the built-in printf command uses the same format as the executable version in /usr/bin.
Format
printf format [argument...]
printf "%10.2f%5d " 10.5 25 |
Format specifier | Value |
---|---|
" | Double quote |