Within BASH, you can use variables. Variables are names that can represent specific information. If you remember your days in math, specifically some stage of algebra, you may recall variables. There were all the letters of the alphabet, mainly X and Y. In BASH, we can use variable names, not just letters.
We will cover other topics to help manipulate the variables and even perform math functions. These can help you make better BASH Scripts that will calculate and manipulate data.
We can find most of this information in the BASH Manual found here.
Assigning Variables
We can create and assign variable names on the go. This means that we do not need to specify variables at the beginning of the script before we can use them.
The variable will exist during the execution of the script. If you create a variable in the terminal, then it exists until the terminal is closed.
Let’s look closer at creating variables. Open a terminal and let’s try a few things.
Type in the following lines one at a time:
The output should be “Hello Bill, you have 5 hours to complete your work.”. This is a very basic example of using variables. Let’s look at what we did. We assigned the value of ‘5’ to the variable ‘x’.
NOTE: Notice that we use lowercase variable names. Any variables we define should stay lowercase. Uppercase variables are system variables, such as ‘PWD’. Do not mix uppercase and lowercase letters since the variable names are case-sensitive. It can become difficult to keep the case the same. If we change the case, then we create a new variable and the other variable data will not be present in the new variable.
The variable for name contains letters and not numbers. Variables that contain letters are strings. The string can contain numbers too or even just numbers. If you want to perform math on a variable, it needs to be a number and not a string. A variable is numeric if the value isn’t in quotes.
The ‘echo’ statement is printing out text we specify and combining it in variable content. To get the content of the variable, place a dollar sign ($) in front of the variable and enclose the variable in curly brackets ({}).
We don’t need the curly brackets, but it is a best practice, as you’ll see later in this article.
Shell Variables
Shell variables are those that are most commonly referred to as System Variables or even Environment Variables.
In a terminal, type the command ‘printenv’ and press enter. You should see a listing of the environment variables for the shell. Notice that they are mostly uppercase letters. A few may be there that are lowercase, which was most likely created by installed applications.
A few shell Variables you may need to know are:
HOME – absolute path to the Home folder of the currently logged in user
USER – username of the user currently logged in
HOSTNAME – the name of the computer
HOSTTYPE – processor type of the system, such as x86_64
PS1 – prompt string for the terminal
SHELL – default shell, such as /bin/bash
PWD – the current directory
OLDPWD – the previous directory
There are many others, but these are ones you’ll need to be aware of for use by a script.
Parameter Expansion
As I had stated, it is best to use curly brackets ({}) when getting the data from the variable. We use this so we can manipulate the data within the variable or get information out of it.
Let’s look at some uppercase and lowercase changes to the screen.
Make two variables:
Issue the command, ‘echo ${name1,}’. The result should be ‘fRED’. The single comma (,) caused the first letter to be changed to a lowercase letter. Try the command, ‘echo ${name1}’. The output should be the original value of ‘name1’, which is ‘FRED’.
By using the expansion commands, we are only changing the output and not the actual value. To change the value, we would have to issue a new assign command to the variable.
Now, try the command ‘echo ${name1,,}’. The output should be ‘fred’. The double-commas (,,) caused the whole variable to become lowercase.
For the variable ‘name2’, issue the command ‘echo ${name2^}’. The result should be ‘Linda’. We changed the first letter to uppercase. The same holds true for the caret (^) symbol as the comma(,). ‘echo ${name2^^}’ will output the value of ‘LINDA’.
If you want to find the length of the data in a variable, use the command ‘echo ${#name2}’. The hashtag (#) causes the length of the variable to be returned, in this case, ‘5’. Since the content of the variable is ‘linda’, the length is ‘5’. If you were to use the variable ‘name1’, the result would be ‘4’.
If we had a variable and only wanted a certain portion of it, then we can select what we want from it.
If we create a variable such as ‘alpha=“abcdefghij”’ we have 10 characters. We index the characters starting at 0 all the way to 9. So, ‘a’ is 0, ‘b’ is 1, ‘c’ is 2 and so on to ‘j’ is 9.
We can print out the first three characters with the command ‘echo ${alpha:0:3}’. The first number, after the colon ), is the starting point. Remember that the first position in the string is 0. The last number is the length we want. With a length of 3, the string returned is ‘abc’.
Another option is to use negative numbers. If the first number is negative, then e start counting at the end of the list and count left. With the command ‘echo ${alpha: -4:3}’ the result would be ‘ghi’. If you use a negative number, you must put a space before the negative (-) sign.
If we left any values out, the default for the first number, or offset, is 0. The default for the second number, or length, is the length of the string. If you leave out the last number, then do not add the last colon ).
Another command is a fill-in for null data. Say we have a variable with nothing in it. We can create the variable with:
Just press enter after the equal sign (=). If you ‘echo’ the value of ‘b’ you get nothing. What if we wanted something to print and not just be blank? The command is ‘echo ${b:-filler}’. You can replace ‘filler’ with a value to replace a blank line. If the variable contains a value, then it prints the value, otherwise, it prints ‘filler’. For example, ‘echo ${b:-empty}’ would print ‘empty’ if ‘b’ has no value.
Command Substitution
Sometimes you need to use the output of a command, such as placing the result into a variable. We can get the system kernel version with the command ‘uname -r’. If we wanted to place the kernel version into a variable named ‘kernelver’ the command is:
For executing a command and retrieving the output, we use regular parenthesis instead of curly brackets. Be sure that the command is valid, and the result is what you need. Run the command in a terminal to verify that the output is what you are needing. Also, be sure the command is valid and you don’t get an error.
Mathematics
We handle math equations just like Command Substitution. The arithmetic operators are:
+ Add
- Subtract
* Multiply
/ Divide
** Exponent
% Modulus
The adding, subtracting, multiplying and division are basic math operators. The exponent and modulus may need explaining.
Exponents are ‘to the power of’ for math. Like three squared is ‘3**2’, which is ‘3*3’. Four cubed, or four to the third power, is ‘4**3’ or ‘4*4*4’.
Modulus is a remainder of a division problem. Dividing in BASH does not give decimals. So, ‘11/4’ has an answer of ‘2’. The modulus of ‘11/4’ is written as ‘11%4’ and the answer is 3. Two times 4 is eight, with three remaining of the eleven. Modulus is an easy way to determine if numbers are divisible evenly by another number because the answer would be ‘0’. such as 100/20 would be 5 with no remainder.
Follow and understand the arithmetic order of operations. Let’s look at those first:
Parenthesis
Exponents
Multiply/Divide
Add/Subtract
We performed these operations in order top to bottom. We performed each line left to right. Let’s look at an example:
2+4*5
There are no parentheses or exponents. We look at Multiply and Divide first. We need to perform ‘4*5’ first, which is ‘20’. Now we perform Add and Subtract next. So, ‘2+20’ is ‘22’.
We can try another example, ‘(2+4)*5’. This is the same as before, we are changing the order by using parenthesis.
We can use variables instead of numbers, or even a mix of both.
The following two examples are the same and will both work:
You can use the dollar signs ($) before the variables or leave them out.
You should be able to manage arithmetic that deals with whole numbers and no decimals. Decimals may be necessary.
Decimal Calculations
Using the terminal a lot, you may understand pipes. We can pipe these commands to a program called ‘bc’ or ‘basic calculator’.
In the previous section, we used the example ‘11/4’. The result is ‘2.75’, but with our math so far, we only get ‘2’.
Let’s see the command and then we’ll cover it:
The response is ‘2.75’.
What is happening is that we are starting the command with the problem we want to be solved. The other item there is ‘scale=2’ separated from the problem with a semicolon (. The ‘scale’ sets the number of decimal places, in this case, 2 numeric places after the decimal. You can change the scale value as you need.
The pipe (|) allows us to pass the math problem and the scale value into the ‘bc’ program. Since the values are being pushed into the program, it will print out the answer to the screen.
Keep in mind that if we want the value in a variable, we can do:
The variable ‘value’ now has the contents of ‘2.75’.
Brace Expansion
We can generate a set of consecutive values. The values can be numeric or alphabetic.
With these examples, we’ll echo them to the screen, but they can easily be input into a variable.
Let’s generate the numbers from 1 to 100 with the command:
This prints the numbers from 1 to 100 on the screen. You can just as easily switch the numbers ‘echo {100..1}’ to have the numbers printed in descending values from 100 to 1.
We can do alphabetic sequencing just as easily:
The first line prints out the lowercase letters a to z. The second line prints the uppercase letters.
You can also skip a certain amount of values, such as counting 1 to 100 by 2.
Conclusion
There are a lot of items covered in this article. Be sure you try the various examples and be comfortable with them.
We will use all the BASH items more as we go along, some more than others.
We will cover other topics to help manipulate the variables and even perform math functions. These can help you make better BASH Scripts that will calculate and manipulate data.
We can find most of this information in the BASH Manual found here.
Assigning Variables
We can create and assign variable names on the go. This means that we do not need to specify variables at the beginning of the script before we can use them.
The variable will exist during the execution of the script. If you create a variable in the terminal, then it exists until the terminal is closed.
Let’s look closer at creating variables. Open a terminal and let’s try a few things.
Type in the following lines one at a time:
Code:
x=5
name=“Bill”
echo “Hello ${name}, you have ${x} hours to complete your work.”
The output should be “Hello Bill, you have 5 hours to complete your work.”. This is a very basic example of using variables. Let’s look at what we did. We assigned the value of ‘5’ to the variable ‘x’.
NOTE: Notice that we use lowercase variable names. Any variables we define should stay lowercase. Uppercase variables are system variables, such as ‘PWD’. Do not mix uppercase and lowercase letters since the variable names are case-sensitive. It can become difficult to keep the case the same. If we change the case, then we create a new variable and the other variable data will not be present in the new variable.
The variable for name contains letters and not numbers. Variables that contain letters are strings. The string can contain numbers too or even just numbers. If you want to perform math on a variable, it needs to be a number and not a string. A variable is numeric if the value isn’t in quotes.
The ‘echo’ statement is printing out text we specify and combining it in variable content. To get the content of the variable, place a dollar sign ($) in front of the variable and enclose the variable in curly brackets ({}).
We don’t need the curly brackets, but it is a best practice, as you’ll see later in this article.
Shell Variables
Shell variables are those that are most commonly referred to as System Variables or even Environment Variables.
In a terminal, type the command ‘printenv’ and press enter. You should see a listing of the environment variables for the shell. Notice that they are mostly uppercase letters. A few may be there that are lowercase, which was most likely created by installed applications.
A few shell Variables you may need to know are:
HOME – absolute path to the Home folder of the currently logged in user
USER – username of the user currently logged in
HOSTNAME – the name of the computer
HOSTTYPE – processor type of the system, such as x86_64
PS1 – prompt string for the terminal
SHELL – default shell, such as /bin/bash
PWD – the current directory
OLDPWD – the previous directory
There are many others, but these are ones you’ll need to be aware of for use by a script.
Parameter Expansion
As I had stated, it is best to use curly brackets ({}) when getting the data from the variable. We use this so we can manipulate the data within the variable or get information out of it.
Let’s look at some uppercase and lowercase changes to the screen.
Make two variables:
Code:
name1=“FRED”
name2=“linda”
Issue the command, ‘echo ${name1,}’. The result should be ‘fRED’. The single comma (,) caused the first letter to be changed to a lowercase letter. Try the command, ‘echo ${name1}’. The output should be the original value of ‘name1’, which is ‘FRED’.
By using the expansion commands, we are only changing the output and not the actual value. To change the value, we would have to issue a new assign command to the variable.
Now, try the command ‘echo ${name1,,}’. The output should be ‘fred’. The double-commas (,,) caused the whole variable to become lowercase.
For the variable ‘name2’, issue the command ‘echo ${name2^}’. The result should be ‘Linda’. We changed the first letter to uppercase. The same holds true for the caret (^) symbol as the comma(,). ‘echo ${name2^^}’ will output the value of ‘LINDA’.
If you want to find the length of the data in a variable, use the command ‘echo ${#name2}’. The hashtag (#) causes the length of the variable to be returned, in this case, ‘5’. Since the content of the variable is ‘linda’, the length is ‘5’. If you were to use the variable ‘name1’, the result would be ‘4’.
If we had a variable and only wanted a certain portion of it, then we can select what we want from it.
If we create a variable such as ‘alpha=“abcdefghij”’ we have 10 characters. We index the characters starting at 0 all the way to 9. So, ‘a’ is 0, ‘b’ is 1, ‘c’ is 2 and so on to ‘j’ is 9.
We can print out the first three characters with the command ‘echo ${alpha:0:3}’. The first number, after the colon ), is the starting point. Remember that the first position in the string is 0. The last number is the length we want. With a length of 3, the string returned is ‘abc’.
Another option is to use negative numbers. If the first number is negative, then e start counting at the end of the list and count left. With the command ‘echo ${alpha: -4:3}’ the result would be ‘ghi’. If you use a negative number, you must put a space before the negative (-) sign.
If we left any values out, the default for the first number, or offset, is 0. The default for the second number, or length, is the length of the string. If you leave out the last number, then do not add the last colon ).
Another command is a fill-in for null data. Say we have a variable with nothing in it. We can create the variable with:
Code:
b=
Just press enter after the equal sign (=). If you ‘echo’ the value of ‘b’ you get nothing. What if we wanted something to print and not just be blank? The command is ‘echo ${b:-filler}’. You can replace ‘filler’ with a value to replace a blank line. If the variable contains a value, then it prints the value, otherwise, it prints ‘filler’. For example, ‘echo ${b:-empty}’ would print ‘empty’ if ‘b’ has no value.
Command Substitution
Sometimes you need to use the output of a command, such as placing the result into a variable. We can get the system kernel version with the command ‘uname -r’. If we wanted to place the kernel version into a variable named ‘kernelver’ the command is:
Code:
kernelver=$(uname -r)
For executing a command and retrieving the output, we use regular parenthesis instead of curly brackets. Be sure that the command is valid, and the result is what you need. Run the command in a terminal to verify that the output is what you are needing. Also, be sure the command is valid and you don’t get an error.
Mathematics
We handle math equations just like Command Substitution. The arithmetic operators are:
+ Add
- Subtract
* Multiply
/ Divide
** Exponent
% Modulus
The adding, subtracting, multiplying and division are basic math operators. The exponent and modulus may need explaining.
Exponents are ‘to the power of’ for math. Like three squared is ‘3**2’, which is ‘3*3’. Four cubed, or four to the third power, is ‘4**3’ or ‘4*4*4’.
Modulus is a remainder of a division problem. Dividing in BASH does not give decimals. So, ‘11/4’ has an answer of ‘2’. The modulus of ‘11/4’ is written as ‘11%4’ and the answer is 3. Two times 4 is eight, with three remaining of the eleven. Modulus is an easy way to determine if numbers are divisible evenly by another number because the answer would be ‘0’. such as 100/20 would be 5 with no remainder.
Follow and understand the arithmetic order of operations. Let’s look at those first:
Parenthesis
Exponents
Multiply/Divide
Add/Subtract
We performed these operations in order top to bottom. We performed each line left to right. Let’s look at an example:
2+4*5
There are no parentheses or exponents. We look at Multiply and Divide first. We need to perform ‘4*5’ first, which is ‘20’. Now we perform Add and Subtract next. So, ‘2+20’ is ‘22’.
We can try another example, ‘(2+4)*5’. This is the same as before, we are changing the order by using parenthesis.
We can use variables instead of numbers, or even a mix of both.
The following two examples are the same and will both work:
Code:
x=1
y=5
echo $(($x+$y))
echo $((x+y))
You can use the dollar signs ($) before the variables or leave them out.
You should be able to manage arithmetic that deals with whole numbers and no decimals. Decimals may be necessary.
Decimal Calculations
Using the terminal a lot, you may understand pipes. We can pipe these commands to a program called ‘bc’ or ‘basic calculator’.
In the previous section, we used the example ‘11/4’. The result is ‘2.75’, but with our math so far, we only get ‘2’.
Let’s see the command and then we’ll cover it:
Code:
echo “scale=2;11/4” | bc
The response is ‘2.75’.
What is happening is that we are starting the command with the problem we want to be solved. The other item there is ‘scale=2’ separated from the problem with a semicolon (. The ‘scale’ sets the number of decimal places, in this case, 2 numeric places after the decimal. You can change the scale value as you need.
The pipe (|) allows us to pass the math problem and the scale value into the ‘bc’ program. Since the values are being pushed into the program, it will print out the answer to the screen.
Keep in mind that if we want the value in a variable, we can do:
Code:
value=$(echo “scale=2;11/4” | bc)
The variable ‘value’ now has the contents of ‘2.75’.
Brace Expansion
We can generate a set of consecutive values. The values can be numeric or alphabetic.
With these examples, we’ll echo them to the screen, but they can easily be input into a variable.
Let’s generate the numbers from 1 to 100 with the command:
Code:
echo {1..100}
This prints the numbers from 1 to 100 on the screen. You can just as easily switch the numbers ‘echo {100..1}’ to have the numbers printed in descending values from 100 to 1.
We can do alphabetic sequencing just as easily:
Code:
echo {a..z}
echo {A..Z}
The first line prints out the lowercase letters a to z. The second line prints the uppercase letters.
You can also skip a certain amount of values, such as counting 1 to 100 by 2.
Code:
echo {1..100..2}
Conclusion
There are a lot of items covered in this article. Be sure you try the various examples and be comfortable with them.
We will use all the BASH items more as we go along, some more than others.