Bash 숫자 연산

Bash, the command-line shell used in Linux, offers various built-in capabilities for performing numerical operations. Whether you need to perform simple arithmetic calculations or more complex math operations, Bash provides useful features that allow you to manipulate numbers effortlessly. In this article, we will explore some common techniques for performing bash 숫자 연산 (numeric operations) in Linux.

1. Arithmetic Operators

Bash supports the basic arithmetic operators: addition (+), subtraction (-), multiplication (*), and division (/). Here’s an example demonstrating how to use these operators:

a=10
b=5

# Addition
result=$((a + b))
echo "Addition: $result"

# Subtraction
result=$((a - b))
echo "Subtraction: $result"

# Multiplication
result=$((a * b))
echo "Multiplication: $result"

# Division
result=$((a / b))
echo "Division: $result"

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2

2. Increment and Decrement

You can also easily increment and decrement numeric values in Bash using the increment operator (++) and decrement operator (–). Here’s how you can use these operators:

n=5

# Increment
((n++))
echo "Increment: $n"

# Decrement
((n--))
echo "Decrement: $n"

Output:

Increment: 6
Decrement: 5

3. Comparison Operators

Bash provides various comparison operators that allow you to compare numeric values. These operators include less than (<), greater than (>), less than or equal to (<=), greater than or equal to (>=), equal to (==), and not equal to (!=). Here’s an example:

a=10
b=5

if ((a > b)); then
  echo "$a is greater than $b"
fi

if ((a < b)); then
  echo "$a is less than $b"
fi

if ((a == b)); then
  echo "$a is equal to $b"
else
  echo "$a is not equal to $b"
fi

Output:

10 is greater than 5
10 is not equal to 5

4. Mathematical Functions

Bash also provides several mathematical functions that enable you to perform complex math operations. Some of these functions include sqrt (square root), exp (exponential), log (natural logarithm), sin (sine), cos (cosine), and more. Here’s an example demonstrating the usage of the sqrt function:

num=16

result=$(bc -l <<< "sqrt($num)")
echo "Square root of $num is $result"

Output:

Square root of 16 is 4.00000000000000000000

Conclusion

Performing numeric operations in Bash is simple and efficient. By utilizing the built-in arithmetic operators, comparison operators, and mathematical functions, you can manipulate numbers and perform calculations easily within your Linux shell scripts. With these capabilities, you have the power to automate complex mathematical tasks and streamline various processes.