Shell variables

Variables

Every programming langauge has some notion of variables to store and retrieve values. They can be typed or untyped. They may or may not need to be declared. They may or may not need to be initialised. You may or may not be allowed to change the type stored.

Variable in the Unix shells

Setting and accessing

To assign a shell variable use '=' with no spaces

x=1   # ok
xyz="some text" # ok
x =1  # no - has a space
x= 1  # no - has a space

To access the value of a variable, prefix it with a '$'

x=1
y=$x
echo Values of x and y are $x, $y

You can see all the variables defined in the current shell by

set 
Many of these variables are set by bash when it runs, such as BASH_ARGC, HISTFILE, HOSTNAME, MACHTYPE, PS1, etc (see "man bash")

Values of variables by default are not seen in subshells

x=1
echo $x
#should have printed '1'
bash
echo $x
# should have printed blank line

Environment

The environment contains all the "global" variables. These are shown by the command

env
Exported variables are visible in subshells.

You can add to the environment by the command export

x=1
export x
export y=2

A one-off mechanism can add to the environment for one command:

x="local export" bash
echo $x
# should have printed local export

You can print all current environment variables with the command env . You see less than with set as it only includes the variables in the environment, and not the other non-environment variables set by the shell (or yourself).

Common variables

Major variables are

Quoting of variables

Motivation: you may set

my_music="My Music"
and then want to change to that directory
cd $my_music
breaks as it expands to cd My Music and the directory "My" doesn't exist. You need to quote it:
cd "$my_music"

Interpretation of a single character is turned off by prefixing it with a backslash `\' as in

echo the amount is \$20
To echo a `\' itself, use \\.

Enclosing something in single quotes '...' turns off all interpretation, including interpretation of $, * and \.

Enclosing something in double quotes "..." allows $variable substitution but no other.

echo The cost is $20
echo The cost is \$20
echo "The cost is $20"
echo 'The cost is $20'

Arcane stuff

Valid characters in variable names are alphanumerics and '_'. An expression like $x.txt is unambiguously the value of x followed by ".txt". Sometimes you might need other text and need to disambiguate the variable from the text: ${x}_txt

If you have an un-assigned variable then its value is "". If you want a default value, then use ${x:-default}

unset x
echo ${x:-bummer}

If you want to replace some text in the value of a variable (e.g. a file extension) then substitute it

x=abcd.txt
echo ${x/.txt/.doc}