Bash: Numeric Variables
Numeric variables are used to store and work with numbers in Bash scripts. Bash treats all variables as strings by default, but you can perform arithmetic operations on integer variables.
Defining Numeric Variables
Integer and floating-point variables
my_integer=10
my_float=10.5 Numbers can be assigned directly without quotes. Bash can perform arithmetic with integers using the ((...)) or $((...)) syntax. Floating-point arithmetic requires external tools.
Accessing and Printing Numeric Variables
Accessing a variable
echo $my_integer Access numeric variables the same way as string variables, using the $ prefix.
Arithmetic Operations
Performing arithmetic with integer variables
a=5
b=3
sum=$((a + b))
echo "Sum: $sum" You can perform arithmetic operations using the $((...)) syntax. Bash supports addition +, subtraction -, multiplication *, division /, and more for integer variables.
Modulo Division
Finding remainder with modulo operator (%)
a=17
b=5
mod=$((a % b))
echo "Modulo: $mod" Use the modulo operator % inside arithmetic expansion to get the remainder of integer division.
Floating-point Arithmetic and Rounding
Rounding a floating-point number (using bc)
num=3.7
rounded=$(echo "$num/1+0.5" | bc)
echo "Rounded: $rounded" Bash does not support floating-point arithmetic natively. Use bc to perform floating-point operations and rounding. The above example rounds 3.7 to the nearest integer.
Casting or Truncating a Floating-point Variable to Integer
Truncating a float to integer (using bc)
num=3.7
int_part=$(echo "$num/1" | bc)
echo "Integer part: $int_part" To cast or truncate a floating-point number to an integer, use bc as shown above. This drops the decimal part and gives the integer portion.
Exporting Numeric Variables
The export keyword
export my_integer=10 The export keyword makes a variable available to child processes or scripts. Without export, a variable is only available in the current shell session.