Bash Subtraction
In Bash scripting, you can perform arithmetic subtraction using arithmetic expansion, the expr command, and the let command. Subtraction is a fundamental arithmetic operation that allows you to calculate the difference between two numbers.
In this tutorial, we’ll guide you through the different methods of performing subtraction in Bash with detailed examples and scenarios.
For a quick overview of the Arithmetic Operations in Bash, you may refer Bash Arithmetic Operations.
Syntax for Subtraction in Bash
The syntax for performing subtraction in Bash can vary depending on the method used. Here are the common approaches:
Subtraction using Arithmetic Expansion:
$((a - b))
Subtraction using expr:
expr a - b
Subtraction using let:
let result=a-b
Subtraction using bc (for floating-point subtraction):
echo "a - b" | bc
Examples of Subtraction in Bash
Let’s go through different examples to see how subtraction can be performed using these methods.
1 Bash Subtraction Using Arithmetic Expansion
Arithmetic expansion is the simplest and most common way to perform subtraction in Bash. It uses the $((...)) syntax to evaluate the expression.
example.sh
#!/bin/bash
# Define two numbers
num1=30
num2=10
# Perform subtraction
difference=$((num1 - num2))
# Display the result
echo "The difference between $num1 and $num2 is $difference."
Output
