Skip to main content

Variables and Arithmetic

Bash variables are loosely typed, which means we don't need to declare whether a variable is a number or a string.

Assignment and Access​

The key rule in Bash is to avoid spaces around the assignment operator (NAME="Gemini", not NAME = "Gemini"). Always use the $ prefix to read a variable's value (e.g., $NAME).

# Assignment (NO spaces!)
NAME="Gemini"
VERSION=1.0

# Accessing
echo "Hello, I am $NAME version $VERSION."

Output:

Hello, I am Gemini version 1.0.

Arithmetic Expansion with (( ... ))​

The (( ... )) syntax is the most modern and readable way to perform integer arithmetic in Bash. It supports common operators like +, -, *, /, and even post-increment/decrement.

((PRICE = 10 + 5))
echo "The total price is: $PRICE"

# Incrementing in place
((PRICE++))
echo "After increment: $PRICE"

Output:

The total price is: 15
After increment: 16

Default Fallbacks​

Bash provides built-in syntax ${VAR:-default} for setting a default value when a variable might be empty or unset. This is great for handling optional arguments or environment variables.

# If USER_INPUT is empty, use 'guest'
USER_INPUT=""
FINAL_USER="${USER_INPUT:-guest}"

echo "User: $FINAL_USER"

Output:

User: guest

Capturing Output with $( ... )​

Command substitution $(command) allows us to assign the result of a command to a variable. This is essential for automation.

CURRENT_DATE=$(date +%Y-%m-%d)
echo "Today's date is: $CURRENT_DATE"

Output:

Today's date is: 2026-04-08
Case Sensitivity

Variable names are case-sensitive. It is a common convention to use uppercase for environment variables (like PATH or USER) and lowercase or camelCase for local script variables.