Bash Variables, Input and Arithmetic
Variables store values in a script so you can use them again and again.
Creating Variables
Write the name, an equals sign and the value, with no spaces around =. Use $ before the name to read the value.
Example
name="Ayesha"
city="Karachi"
age=20
echo "$name lives in $city and is $age years old."Ayesha lives in Karachi and is 20 years old.
name = "Ayesha" (with spaces) is a common mistake. Bash thinks name is a command and shows "command not found".
Curly Braces
Use ${name} when the variable is joined to other text, so Bash knows where the name ends:
Example
file="report"
echo "${file}_2026.txt"
echo "$file_2026.txt"report_2026.txt .txt
The second line prints only .txt, because Bash looked for a variable called file_2026, which does not exist.
Single and Double Quotes
| Quotes | Variables expanded? | Example | Prints |
|---|---|---|---|
Double " " | Yes | "Hi $name" | Hi Ayesha |
Single ' ' | No | 'Hi $name' | Hi $name |
Example
name="Ali"
echo "Hello $name"
echo 'Hello $name'
echo "Price: \$50"Hello Ali Hello $name Price: $50
A backslash \ before $ stops it from being treated as a variable. Always put variables in double quotes, especially file names that may contain spaces.
Command Substitution
$(command) runs a command and puts its output in place. You can store the result in a variable:
Example
files=$(ls | wc -l)
today=$(date +%Y-%m-%d)
echo "There are $files files here."
echo "Backup name: backup-$today.zip"This prints the real number of files and today's date, for example backup-2026-10-15.zip.
Reading User Input
read waits for the user to type something and saves it in a variable. -p shows a prompt first.
Example
#!/bin/bash
read -p "What is your name? " name
read -p "Which course do you want? " course
echo "Welcome $name! You chose $course."If the user types Hamza and Web Development, the script prints:
What is your name? Hamza Which course do you want? Web Development Welcome Hamza! You chose Web Development.
Use read -s for passwords, so the typed characters are not shown.
Arithmetic
Bash does whole-number maths inside $(( )):
Example
price=350
qty=4
total=$((price * qty))
echo "Total: Rs $total"
echo "Half: $((total / 2))"
echo "Remainder: $((17 % 5))"
count=1
((count++))
((count += 10))
echo "Count: $count"Total: Rs 1400 Half: 700 Remainder: 2 Count: 12
Inside $(( )) you do not need $ before variable names. Bash has no decimals here: $((7 / 2)) is 3. For decimals, use the bc tool: echo "7 / 2" | bc -l.
Environment Variables
Some variables are already set by the system. They are written in capital letters:
| Variable | Holds |
|---|---|
$HOME | Your home folder |
$USER | Your user name |
$PATH | Folders where Bash looks for commands |
$PWD | The current folder |
Use export NAME=value to make a variable available to programs started from your script.
Exercise
Exercise
Which line correctly stores the value 10 in a Bash variable?
