Variables and parameters in the bash shell

Variable assignment is a mechanism by which you can associate a value you need to recall with a label that is easy to remember or is descriptive. In the bash shell, a variable is a single word composed of upper or lower case alpha characters (a-zA-Z), the underscore (_), and all digits (0-9) as long as the 1st character of the variable name is not a digit. Remember that Unix is case sensitive, so the variable names VAR, Var, and var are recognized as different variables.

Parameters are variables created or used by the shell for special purposes and that often break the rule above about valid characters. You, the user, can access shell parameters and their contents but will, usually, not be able to directly change the values stored in them.

Creating a variable is a simple process. At the prompt, specify the variable name, followed by an equal sign (=) and then the value to remember. There must be no spaces on either side of the equal and the value must be quoted if contains space.

firstname=John
myname="John Berezinski"

To access the variable's contents, precede the name with a $ (dollar).

echo $myname
John Berezinski

Because of the way the command line is processed, you can even reference a variable's contents while reassigning its contents.

firstname="$firstname A."
echo $firstname
John A.

Notice the double quotes. If you reference a variable in a quoted string and you desire the contents of the variable rather than the name itself, use double quote.

To remove a defined variable, use unset.

unset firstname

A variable normally is only defined in the current shell or program. A variable of this type is called a local variable. If you were to run a shell script or other program, it would know nothing about a variable you have defined outside the program.

However, you can promote a variable so that it will be copied or exported to the environment of any program run from the command prompt. A variable that has been promoted to such a state is called a global or an environmental variable. The command to perform this promotion is export.

project=assn01
export project

export ME="John"

Either form works. Once a variable is marked as exportable, it will be exported to any program started under the current shell and also any program started by that program. Unless the export is disabled.

To disable the exporting of a variable, use export with the -n option.

export -n ME

Although not required, it is a standard practice to use capital letters for a variable name that will be exported.

#( This 1st command sets the login shell to ignore the [ctrl]d )

set -o ignoreeof

#( The following ps command lists processed running and you should see one copy ofbash running assuming you do not have other programs running in the background.) ps
#(Create a local variable and display its value.)

var="valuable"
echo $var

#(Now start a new copy of thebash shell. The ps should now list 2 copies of bash.)

bash
ps
echo $var

#( Now exit the new copy of bash. )

[ctrl]d

#( Export the var variable, start a new shell again, use ps to confirm a new shell is running again and see if var has a value now. )

export var
bash
ps
echo $var
[ctrl]d

#(Now disable the exporting of var and try again.)

export -n var
bash
ps
echo $var
[ctrl]d

Occasionally, you may wish to protect a variable from being changed or unset. Use readonly to protect a variable.

readonly var

Once a variable is marked readonly, it cannot be changed or unset. You also cannot remove the readonly status. You must terminate the shell or program in which the readonly status was implemented. However, the readonly status exists only in the current shell or program. If you export the variable, it will be changeable in the new program or shell.

bash uses two additional commands to create variables. They are declare and typeset and are identical. bash is a modelled on the original Unix Bourne shell but with liberal borrowing of ideas from the C-shell and Korn shells, two popular alternative shells for the Unix environment.

When used to create single value (scalar) local variables, they work indentically to the simple var=value syntax. However, they can also be used to define array variables, export a variable or function, or make it readonly, and do more than one of these with a single command.

declare -axr DATA='([1]="red" [4]="green" [8]="blue" )'

creates the data variable as an array, assigns values to 1st 3 elements, makes it exportable and readonly in the current shell.

And now a word on array variables. Array variables were not part of the original Bourne shell but are modelled after array variables in the Korn shell.

To create an array variable, you must use declare or typeset and the -a option or initialize the elements individually. The array created is numerically indexed and values will be assigned starting from index 0 unless specifically targeted. The following is one of the simplest examples :

declare -a myary='( red blue green )'

The quotes are needed because you are using spaces to separate the elements and because the parenthesis have a different meaning to shell if unquoted.

This will create an initial variable with three elements starting at index zero and stored in ascending index order.

You may explicitly target certain element indexes either while initializing the array or later.

declare -a DATA='([1]="really red" [2]="glorious green" [4]="brilliant blue" )'
DATA[3]="putrid puce"'

The second assignment demonstrates initializing an individual element. This can also be used to change a stored value.

To view an element of the variable, use the variables name and the index.

echo ${DATA[4]}

The braces, {}, are required because the brackets are also used by the shell for filename wildcards. To see all elements in an array variable, use * or @ as an index value.

echo ${DATA[*]}

Braces are also used with a variable when you wish to concatenate its contents to a constant string.

abode=boat
echo $abode
boat
echo house$abode
houseboat
echo $abodehouse

The line under the last echo is blank because the variable $abodehouse is not defined. To concatenate the contents of abode with the string house, use the braces.

echo ${abode}house
boathouse


Keyword variables and parameters.

Keyword variables and parameters are variables that are internally defined by the command shell or that are created in the system wide configuration file the shell reads when it starts. We will examine this file a little later.

Keyword variables may be either local or global. To see what local variables are set when you log in, run set and to see exportable variables already defined, run env. The set may also print out all shell functions already define, so this may be a long list.

We have already worked with a few of the available keyword variables. HOME is the path to the user's home directory and is set from the user's password entry when login occurs. PATH is a list of possible locations to search for an invoked command. PATH is initialized from the system wide configuration file and the user's personal configuration file for the shell.

PS1 is the customizable prompt displayed in the terminal screen. To set the prompt to display the current working directory followed by a greater than sign, set PS1 to :

PS1="\w > "

For more configuration options for the prompt, see the PROMPTING section of the man page on bash.

PS2 is the prompt used when a quote or complex command is started on one line and continued on anther line. This prompt indicates that the command or quote is not yet complete.

Pages 283-292 of our text book, "A Practical Guide to Linux" by Sobell, describes other keyword variable available in bash. We will look at a few others when the appropriate topic is covered.

You may customize the contents of most of these shell variables. However, it ill advised to unset any of them. Even if recreated, some of them may no longer function correctly.

Parameters are a subset of the shell variables. They are often a single character that is not a-zA-Z or are digits. Unlike regular shell variables, most parameters cannot be directly set by the user but are often modified be actions the user takes. Like other variables, the are referenced by preceding them with the $.

* The asterisk represents all arguments passed into a shell, shell script, or commmand when it was invoked.
@ Like *, the at represents all arguments passed into a shell, shell script, or commmand when it was invoked except that it will recognize and honor quoted strings. This will be made clear when we cover shell scripts.
# The octhorpe represents the count of all arguments passed into a shell, shell script, or commmand when it was invoked. The command itself is not counted.
? The question mark represents the status of the last command run in the foreground. Zero represents success and a value between 1 and 255 represents failure. The most common failure is 1 but a command may use others to indicate specific failure types.
$ The dollar sign represents process id of the current shell. If you are running a shell script, it will be the pid for the script.
! The exclaimation sign represents process id of the last background process to terminate.
0 or other integers Called positional parameters, these reference the specific argument included on the command line when the shell or shell script was invoked. $0 refers to the command's own name. We will look at positional parameters in more detail when we cover shell scripts.


Lets take another look at positional parameters.

Positional Parameters