0
0
Bash Scriptingscripting~5 mins

Integer variables in Bash Scripting

Choose your learning style9 modes available
Introduction
Integer variables store whole numbers so you can do math and count things in your script.
Counting how many files are in a folder.
Adding numbers like scores or totals.
Using loops that run a set number of times.
Tracking how many times something happens.
Doing simple math calculations in your script.
Syntax
Bash Scripting
declare -i variable_name=number
# or simply
variable_name=number
Use 'declare -i' to tell bash this variable is an integer.
You can assign a number directly without quotes.
Examples
This creates an integer variable named count with the value 10.
Bash Scripting
declare -i count=10
This assigns 5 to variable number. Bash treats it as a string but can do math if used properly.
Bash Scripting
number=5
Declares total as integer, sets it to 7, then adds 3 to it.
Bash Scripting
declare -i total
 total=7
 total=total+3
Sample Program
This script creates an integer variable score, adds points to it, and prints the final score.
Bash Scripting
#!/bin/bash

# Declare integer variable
declare -i score=0

# Add points
score=score+10
score=score+5

# Print the score
 echo "Your score is $score"
OutputSuccess
Important Notes
Without 'declare -i', bash treats variables as strings, so math needs special syntax like $(( )) to work.
Using 'declare -i' makes bash automatically calculate math expressions assigned to the variable.
Always use quotes around variables when printing to avoid word splitting or errors.
Summary
Integer variables hold whole numbers for math in bash scripts.
Use 'declare -i' to make a variable an integer.
You can add or change integer variables with simple math expressions.