The bash scripts allow for the use of variables. The variable declaration is:
variable_name = value
The scope of this variable is the script where it was created in. To make it available to other programs or scripts, you can write:
export variable_name
To print on the screen the value of a variable you can write (remember to put the dollar sign):
echo $variable_name
To assign the value of a variable to another variable, you can write:
x=$y
Quotes usage
In the bash there are three strings delimiters: the grave accent, the single quotes and the double quotes. Each one gives a different behaviour:
- Double quotes: (that is "): visualize a string substituting it with its value.
- Single quotes (that is '): don't substitute the value of a variable to its name.
- Grave accents (that is `): substitute to the string the result of its execution (useful for example when you want to save the output of a command in a variable).
Let's see an example
#!/bin/bash
x=10
echo " The variable is: $x" #Prints " The variable is: 5"
echo ' The variable is: $x' #Prints " The variable is: $x"
Arithmetical operations
To execute arithmetical operations you can use two different syntaxes:
- expr included between grave accents (be careful not to use the apostrophe!).
- double parenthesis with the dollar sign.
This is an example:
#!/bin/bash
x=5
x=`expr $x + 1`
x=$(($x+1))
echo $x
The allowed mathematical operations are:
Symbol | Meaning |
+ | Sum |
- | Subtraction |
* | Multiplication |
/ | Division |
% | Module or remainder |