Variables

A variable is a temporary store of alphanumerical information, that can be set or retrieved within a script / program and manipulated to produced an effect on that or another variable.

 

Variables are, usually, given a user friendly name which then has a value assigned to it.

 

In shell scripting, variables are declared by simply assigning a value upon the variable name, stated on the left e.g. myvar=17

 

The shell script can then read this variable by preceding a $ symbol against its name e.g. $myvar

 

Variable names can be alphanumeric, UPPER or lower case, or a mixture of both and must begin with an alphanumeric character or underscore character (_), followed by one or more alphanumeric or underscore characters.

 

Also, variables names are case-sensitive, just like filenames. i.e all the following are valid different variable names:

  • MYVAR
  • myvar
  • mYvAr

 

Variables are declared by use of an equals symbol with no spaces either side:

  • myvar=20
  • vegtable=potato

 

Do not put spaces on either side of the equal sign when assigning a value to variable, or it will result in an error.

 

If you need to use a space within a variable value it must be encapsulated within quotes. Single quotes will interpret the value literally, whilst double quotes will allow any encapsulated variable to be interpreted within the value being defined:

  • myvar='This will be interpreted exactly as it is written'
    • When echo'd would produce: This will be interpreted exactly as it is written
  • bike="Ducati Desmosedici"
  • motorbikes="My $bike is fun to ride!"
    • When $motorbikes is echo'd it would produce: My Ducati Desmosedici is fun to ride!

 

You can also define a NULL variable as follows (NULL variable is variable which has no value at the time of definition):

  • myvar=""

 

#!/bin/bash

# Set var hi
hi="Hello, "

# Set var there
there="World!"

echo "$hi $there"

 

Output:

Hello, World!

 

 

You may also sometimes see a variable being used within curly braces {}, which is particularly useful to avoid any ambiguity when referring to a specific variable:

#!/bin/bash

# Set var hi
hi="Hello, "

# Set var there
there="Wor"

echo "${hi} ${there}ld!"

 

Output:

Hello, World!

 

*notice:

  • the $there variable just being used for "Wor"; the first half of World!
  • the variables are expanded within the double quotes