Friday, August 19, 2016

Up and Running with Bash Scripting - 5

Arithmetic operations:
Working with numbers in Bash is pretty straight forward. To tell the interpreter that you're going to do math, you need to wrap an expression up in double parenthesis. If you're assigning the result of an arithmetic expression to a variable, the paren's need to start with a dollar sign. The expression inside the parenthesis can use either literal numbers or variables.

Example: To define, wrap expression in double parenthesis; (( expression ))
assiging the result of an arithmetic expression to variable, it need to start with a dollar sign.

val=$(( expression ))

supported arithmetic operations:

1. Exponentiation : $a ** $b
2. Multiplication : $a * $b
3. Division : $a / $b
4. Modulo : $a % $b
5. Addition $a + $b
6. Subtraction : g

Example
example script:
--
#!/bin/bash
# This is a basic bash script
a=2
e=$((a+2))
echo $e
=================================================================
Comparison operation:

One of the primary reasons you might want to write a script rather than execute commands line by line is to incorporate some logic into what you're doing.
For this, comparisons can be very useful. We do this with double square brackets.

[[ expression ]]

It's important to keep spaces between the sets of brackets and the expression. This expression returns 1 or 0 for failure or success. $? is used to return the value

Bash supports the standard compliment of comparators. Less than, greater than, less than or equal to, greater than or equal to, equal, and not equal. These work within the double square brackets to compare strings

 I'll test to see if one string is equal to another and then echo the return value with $? In this test context, you can use a single or a double equals sign to test for equality

Example:
#!/bin/bash
# This is a basic bash script
[[ "cat" == "cat" ]]
echo $?

[[ "cat = "dog" ]]
echo $?

The first test for cat equals cat returns 0 for success. And the next one cat equals dog returns 1 or failure
-------
For working with integers you have to use a set of operators that tell Bash to compare the terms as numbers. we've got the same operations, but the operators are different. A dash and a few letters. - lt for less than, - gt for greater than, - le for less than or equal to, - ge for greater than or equal to, - eq for equality, and - ne for not equal.

#!/bin/bash
# This is a basic bash script
[[ 20 -gt 100 ]]
echo $?

Supported logical operators:
Logical AND = [[ $a && $b ]]
Logical OR  = [[ $a || $b ]]
Logical Not = [[ ! $a ]]

string null value:

is null ?  [[ -z $a ]]
is not null ? [[ -n $a ]]

example script:

#!/bin/bash
# This is a basic bash script
a=""
b="cat"
[[ -z $a && -n $b ]]
echo $?

Above script will return 0 or success.