Practice exercise in Bash Basics Series #4: Arithmetic Operations

If you are following the Bash Basics series on It’s FOSS, you can submit and discuss the answers to the exercise at the end of the chapter:

Fellow experienced members are encouraged to provide their feedback to new members.

Do note that there could be more than one answer to a given problem.

4 Likes

@abhishek ,
That link does not work

It says… itsfoss.com host error

Must have been a temporary glitch? Worked for me this morning, still works…

Note also - a few years back, I started a thread about doing maths in the shell :

Anyway - I’d only just started learning how to use awk to do floating point arithmetic (in preference to using “bc”) - and when I saw this new thread, I went looking for some older shell scripts I might have written using awk to do floats, and couldn’t find a single example!

1 Like

Should be temporary but do let me know if it persists :hourglass_flowing_sand:

9 posts were split to a new topic: It’s FOSS website returns server error 520

About the ((...)) notation, it should be noted that:

  1. We can omit $ for variables in any arithmetic expression.
    For example, we can write res=$((var1 + var2)) instead of res=$(($var1 + $var2))
    As this rules applies for any arithmetic expression, not only within ((...)). For example, the following are valid:
    • i=3; str="abcdefgh"; echo ${str:i:i+1} (will be evaluated as echo ${str:3:4})
    • declare -i i=3; i=i+2; i+=5 (i value is 10)
  2. the assignments operators (=, +=, <<=, ^= etc…) are valid in ((...)) construction. We can write ((res = var1 + var2)) instead res=$((var1 + var2))
  3. ((...)) can be nested. ((i = 2 + ((j = 4 * 10)))) will give i=42 and j=40.
  4. I think you should give the full list of arithmetic operators, including comma, assignment, comparison, logical, bitwise and expr?expr:expr. They allow to have complex arithmetic expressions, such as ((i=3, j=4, k=i>j? i:j)) (k will be the max of i and j).
2 Likes

Thanks for the additional inputs.

I should add the first 3,

About the 4th one, logical operators and bitwise operators will be covered separately.

If you add the first 3, maybe you could also consider to include <</>> (and <<=/>>=) operators, as they are actually a multiplication/division by a power of 2: (( i <<= p )) is (( i *= ( 2 ** p ) )) and (( i >>= p )) is (( i /= ( 2 ** p ) )).
And also add an important warning on overflow, when we try to calculate over LONG_MAX and under LONG_MIN (defined in /usr/include/limits.h).
For example, on my system, LONG_MAX is 9223372036854775807, and we have an overflow with echo $((9223372036854775807 + 1)). bc (or my favorite dc) would be preferable in these cases, when numbers may go high/low.