DEV Community

Cover image for Linux Bash Control Flow and Arithmetic
Damon Marc Rocha II
Damon Marc Rocha II

Posted on

Linux Bash Control Flow and Arithmetic

As promised, here is the next section in my Bash blog series; control flow and arithmetic. These concepts are not too hard to follow but require knowledge of their basic structure. The first section here covers control flow.

Control Flow


Control flow in bash allows for comparison using <, >, =, and so many more operators. With this, one can compare variables to one another, or operate on files under certain conditions.
I will give a basic example here using variables:

read x
read y
if [[ $x > $y ]]
then
    echo "X is greater than Y"
elif [[ $x < $y ]]
then 
    echo "X is less than Y"
else
    echo "X is equal to Y"
fi

Enter fullscreen mode Exit fullscreen mode

For this to successfully run it is important to format the control statements as shown above; especially the spacing inside of the [[]]. Other than that, the example above is a classic and really speaks for itself.

Alt Text

Arithmetic


It is possible to solve complex calculations using bash, and as a bonus, it is not hard to format the output.

Using these mathematical statements:

  • 5+50*3/20 + (19*2)/7
  • -105+50*3/20 + (19^2)/7
  • (-105.5*7+50*3)/20 + (19^2)/7

the program below will output the solution rounded to the third decimal.

read math
printf "%.3f" `echo $math |bc -l`
//=> first read 17.929
//=> second read -45.929
//=> third read 22.146
Enter fullscreen mode Exit fullscreen mode

Mathematical statements can be read into a variable. However, to show their solution you must either wrap the variable in double parens $((..)), if you are only using integers, or use the |bc -l command if your output needs to be floating point numbers. Then this can be inserted into an echo as shown above. For more about bc go here.
To format the output the printf must come before the echo. Then the number after the % formats your output to that decimal place.
These commands are really useful foundations of bash that will come into play quite often. Hope you guys enjoyed this, I will get another post up sometime this week covering String Slicing and formating.

Top comments (0)