Linux and Networking

Linux and Networking

4.16. The let command and the arithmetic operators.

So far we have been looking at basic concepts that will allow us to carry out most of the shell scripts. In this entry we will see more extremely useful concepts that will help us a lot when creating shell scripts such as the let command or the random command or also the logical operators.

 

Before seeing how the let command works, let’s see what arithmetic operators it uses:

 

+ sum

– subtraction

* multiplication

/ division

** exponentiation

 

Let’s look at an example of using the let command that uses the exponentiation operator:

 

let “z=5**3”

echo “z = $z”

z = 125

 

Another example using the % (modulo) operator.

 

let “z=5%3”

echo “z = $z”

z=2

 

With let we can also use the operators += (more equal) and -= (less equal):

 

var=3

let “var += 5”

echo $var

8

 

As we see, the command let «var += 5» increments the variable var by 5. And that’s not all, we can also use the *= operator (multiplied equals), /= (divided equals) and %= (module equals):

 

var=3

let “var *= 5” #which is the same as doing var=var*5

echo $var

15

 

Suggested exercise

Write a script that performs basic arithmetic operations like:

+ sum

– subtraction

x multiplication

/ division

The script will be called dale.sh and will work as follows:

$ ./dale 20 / 4

5

 

Implement it so that it works with many arguments.

The Demeter Project