Bash 숫자 연산자

When working with Bash scripting in Linux, you often need to perform numeric calculations or manipulate numerical values. Bash provides a range of numeric operators that allow you to perform basic arithmetic operations and more advanced calculations. In this blog post, we will explore these operators and learn how to use them effectively.

Addition Operator (+)

The addition operator is used to add two or more numbers together. It is represented by the plus sign (+). For example, to add two numbers num1 and num2, you can use the following code:

result=$((num1 + num2))

Subtraction Operator (-)

The subtraction operator is used to subtract one number from another. It is represented by the minus sign (-). To subtract num2 from num1, you can use the following code:

result=$((num1 - num2))

Multiplication Operator (*)

The multiplication operator is used to multiply two numbers. It is represented by the asterisk (*) symbol. To multiply num1 and num2, you can use the following code:

result=$((num1 * num2))

Division Operator (/)

The division operator is used to divide one number by another. It is represented by the forward slash (/). To divide num1 by num2, you can use the following code:

result=$((num1 / num2))

Note that in Bash, division returns an integer result. If you want to perform floating-point division, you can use an external tool like bc (basic calculator) as follows:

result=$(echo "scale=2; $num1 / $num2" | bc)

Here, the scale=2 sets the number of decimal places to 2.

Modulus Operator (%)

The modulus operator is used to find the remainder when one number is divided by another. It is represented by the percent sign (%). To find the remainder of num1 divided by num2, you can use the following code:

result=$((num1 % num2))

Increment (++)

The increment operator is used to increase the value of a variable by 1. It is represented by two plus signs (++). For example, to increment the value of num by 1, you can use the following code:

((num++))

Decrement (–)

The decrement operator is used to decrease the value of a variable by 1. It is represented by two minus signs (–). To decrement the value of num by 1, you can use the following code:

((num--))

These are the basic numeric operators available in Bash for performing arithmetic operations. You can combine these operators to create complex calculations and algorithms in your Bash scripts.

Remember to test your code thoroughly and handle potential errors or divide-by-zero scenarios to ensure the reliability and accuracy of your scripts.

I hope this blog post helps you understand and utilize the numeric operators available in Bash for Linux. Happy scripting!