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"
age =35
total= 16.5
Another useful type of user-defined variable is the array. An array can hold multiple values. So, if you have tens of values you want to use, you should use arrays instead of filling your script with variables.
To declare an array, just enclose its elements between brackets, like this:
#!/bin/bash
myarr=(one two three four five)
To access a specific array element, you can specify its index like this:
#!/bin/bash
myarr=(one two three four five)
echo ${myarr[1]} #prints two which is the second element
The index is zero based.
To print the array elements, you can use an asterisk, like this:
#!/bin/bash
myarr=(one two three four five)
echo ${myarr[*]}
To remove a specific element from the array, you can use the unset command:
#!/bin/bash
myarr=(one two three four five)
unset myarr[1] #This will remove the second element
unset myarr #This will remove all elements