created on | April 18, 2022 |
Variable names are case sensitive. They have to start with a lower or an upper case letter or an underscore.
Do not use all upper case variable names. The general convention is that all upper case variables (with underscores) are reserved for environment variables. Nevertheless, there are plenty of shell scripts in the wild that use all upper case variable names.
general form a variable declaration:
Read-only variables can be declared with , i.e.:
The shell does not have strict typing. However, integer variables can be declared with , i.e.:
Variables are referenced by prepending the variable with a and wrapping the variable name in curly braces:
One can omit the curly braces in most situations, but using the curly braces when referencing variables safeguards against a lot of errors, i.e.:
Curly braces are mandatory in the following cases:
If the variable contains blanks, it should be quoted. If a variable with blanks is given as an argument to a command and the variable is not quoted, the command will process the variable not as a single argument but will process the veriable as a number of arguments, separated by the blanks in the variable.
In the example below, the shell takes the variabe sentence as a number of string arguments, separated by blanks. printf is invoked for each of these arguments, which is why every word in the variable sentence is printed line by line:
If the variable is quoted, the shell takes the variables as one argument, and the variable is printed on a single line as one might expect:
The best habbit is wrap all variable names in curly braces and to quote all variables unless you are sure that a variable does not contain blanks.
in a shell script you have access to some special shell script variables:
the following special shell variables have the same meaning as in the shell:
The array , which contains the shell script arguments, can be shifted left with . For each invocation of shift, the array values are shifted left one position (or index). Note, that the array of arguments always starts at index 1. is not modified by and retains its original value.
The following example illustrates this. running the script with the following content:
with the arguments ‘so’ ‘what’ results in the following output:
shell scripts have access to all environment variables, that is, all the variables you get listed when running the command in a shell. A shell script can export environment variables only to commands and child processes which the shell scripts initiates. A shell script invoked from the command line cannot export variables back to the command line environment.