The + operator

This is like what we see at primary school; this operator allows us to add an integer to the value of the variable, as we can see in the following example:

#!/bin/bash
echo "Hello user, please give me a number: "
read user_input
echo "And now another one, please: "
read adding
addition=$((user_input+adding))
echo "The number is: ${user_input:-99}"
echo "The number added of ${adding} is: ${addition}"

Now time to invoke the script:

zarrelli:$ ./useraddition.sh 
Hello user, please give me a number:
120
And now another one, please:
30
The number is: 120
The number added of 30 is: 150

As you have probably noted, we used a double parenthesis construct $(( )) to perform this arithmetic expansion and evaluation: in short, it is as we said, expand and evaluate, then return the value. It is a common notation in binary operators and also allows us to quote special characters as if we'd enclosed them into double quotes, so we are not compelled to escape that. The only exception is the double quote, which still must be escaped. Do not worry; we will read more about special characters and how to quote them later on.

Now, just try to run the script and give no numbers:

The number is: 99
The number added of is: 0

The number 99 is not an assignment, just a default value we were returned in case the variable held no usable values, but the first and second variables have no assignment so adding one value to the other leads us to 0.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.246