Skip to content

Latest commit

 

History

History
70 lines (54 loc) · 2.45 KB

2.md

File metadata and controls

70 lines (54 loc) · 2.45 KB

Chapter 4: The Conditional Conundrums 🤔

2 - Arithmatic operations with conditionals

Arithmetic Operations with Conditionals in Linux Shell Scripting

Overview

In Linux shell scripting, arithmetic operations can be combined with conditional statements to perform actions based on specific numerical conditions. These operations allow scripts to make decisions and control program flow based on the outcome of mathematical expressions. This README.md file provides an overview of how arithmetic operations can be used in conjunction with conditionals in Linux shell scripting, along with examples demonstrating their usage.

Arithmetic Operations with Conditionals

Arithmetic operations in shell scripting are typically performed using the (( )) construct. Conditionals can be used to evaluate the result of these operations and execute specific code blocks based on the outcome. Here are some common arithmetic operators used in conditionals:

  • Equal to (==): Checks if two values are equal.
  • Not equal to (!=): Checks if two values are not equal.
  • Greater than (>): Checks if one value is greater than another.
  • Greater than or equal to (>=): Checks if one value is greater than or equal to another.
  • Less than (<): Checks if one value is less than another.
  • Less than or equal to (<=): Checks if one value is less than or equal to another.

Examples

Example 1: Checking if a Number is Even or Odd

#!/bin/bash

# Check if a number is even or odd
number=10

if (( number % 2 == 0 )); then
    echo "$number is even"
else
    echo "$number is odd"
fi

Example 2: Determining the Maximum of Two Numbers

#!/bin/bash

# Determine the maximum of two numbers
num1=20
num2=30

if (( num1 > num2 )); then
    echo "Maximum number is $num1"
else
    echo "Maximum number is $num2"
fi

Example 3: Checking if a Number is Positive, Negative, or Zero

#!/bin/bash

# Check if a number is positive, negative, or zero
number=-15

if (( number > 0 )); then
    echo "$number is positive"
elif (( number < 0 )); then
    echo "$number is negative"
else
    echo "$number is zero"
fi

Conclusion

These examples demonstrate how arithmetic operations can be combined with conditionals to perform different actions based on numerical conditions in Linux shell scripting.

⬅️Previous-----------Next ➡️

Table of contents 🚀