User-defined variables

To declare a variable, just type the name you want and set its value using the equals sign (=).

Check out this example:

#!/bin/bash 
name="Mokhtar" 
age=35 
total=16.5 
echo $name  #prints Mokhtar 
echo $age   #prints 35 
echo $total #prints 16.5 

As you can see, to print the variable's value, you should use the dollar sign ($) before it.

Note that there are no spaces between the variable name and the equals sign, or between the equals sign and the value.

If you forget and type a space in between, the shell will treat the variable as if it were a command, and, since there is no such command, it will show an error.

All of the following examples are incorrect declarations:

# Don't declare variables like this: name = "Mokhtar" ...

Get Mastering Linux Shell Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.