Can you provide an example of performing arithmetic operations with shell variables?

QuestionsQuestions8 SkillsProDec, 12 2025
0129

Yes, absolutely! We just covered this in the step.

Here's a simple example of performing arithmetic operations with shell variables in Bash, similar to what you did in the arithmetic.sh script:

#!/bin/bash

# Define two variables
num1=10
num2=5

# Perform addition
sum=$((num1 + num2))
echo "Sum: $num1 + $num2 = $sum"

# Perform subtraction
difference=$((num1 - num2))
echo "Difference: $num1 - $num2 = $difference"

# Perform multiplication
product=$((num1 * num2))
echo "Product: $num1 * $num2 = $product"

# Perform division
quotient=$((num1 / num2))
echo "Quotient: $num1 / $num2 = $quotient"

# Perform modulus (remainder)
remainder=$((num1 % num2))
echo "Remainder: $num1 % $num2 = $remainder"

# Increment a variable
num1=$((num1 + 1))
echo "num1 after increment: $num1"

# Decrement a variable
num2=$((num2 - 1))
echo "num2 after decrement: $num2"

Explanation:

  • $((expression)): This is the Bash syntax for performing arithmetic operations. Everything inside the double parentheses ((...)) is treated as an arithmetic expression.
  • Variables within arithmetic expressions: You can use shell variables directly inside $((...)) without needing to prefix them with $ (e.g., num1 + num2 instead of $num1 + $num2). However, using the $ sign explicitly for variables inside arithmetic expressions like $(($num1 + $num2)) also works and sometimes can improve clarity for beginners or in complex scenarios.
  • Operators: Standard arithmetic operators like +, -, *, /, % (modulus/remainder) are supported.
  • Assignment: The result of the arithmetic operation is assigned back to another shell variable (e.g., sum=$((num1 + num2))).
  • echo: Used to display the results.

How to try this yourself:

  1. Open your WebIDE or a web terminal.
  2. Create a new file, for example, my_arithmetic.sh:
    touch my_arithmetic.sh
  3. Open my_arithmetic.sh (e.g., nano my_arithmetic.sh) and paste the code above into it.
  4. Save and close the file.
  5. Make the script executable:
    chmod +x my_arithmetic.sh
  6. Run the script:
    ./my_arithmetic.sh

You should see output similar to this:

Sum: 10 + 5 = 15
Difference: 10 - 5 = 5
Product: 10 * 5 = 50
Quotient: 10 / 5 = 2
Remainder: 10 % 5 = 0
num1 after increment: 11
num2 after decrement: 4

This is exactly what the "Arithmetic Operations" section of your current lab step teaches! Feel free to refer back to that section for more details.

0 Comments

no data
Be the first to share your comment!