Linux and Bash course menu
Bash Variables and Quoting Explained
Create Bash variables, understand single and double quotes, avoid word-splitting bugs, do arithmetic with $(( )), use default values, and read command output into variables.
On this page
Variables#
Assign with = and no spaces, and read with $:
name="Asha"
age=24
echo "$name is $age"Asha is 24Use ${name} when text follows immediately:
file="report"
echo "${file}_2026.txt"
echo "$file_2026.txt"report_2026.txt
.txtThe second line looks for a variable called file_2026, which is empty.
Bash variables have no types. Everything is text, unless used in arithmetic. Uppercase names are usually for environment variables, and lowercase for your own.
Single and double quotes#
city="New Delhi"
echo "I live in $city"
echo 'I live in $city'I live in New Delhi
I live in $cityWhy quoting matters#
Without quotes, Bash splits a value on spaces, and it expands wildcards. This is the source of many script bugs:
file="my report.txt"
touch "$file"
ls -l $file 2>&1 | head -n 2
echo ---
ls -l "$file" | awk '{print $NF}'ls: cannot access 'my': No such file or directory
ls: cannot access 'report.txt': No such file or directory
---
report.txtUnquoted, ls received two names: my and report.txt.
Command substitution#
$(...) stores a command's output:
count=$(ls -A | wc -l)
today=$(date +%Y)
echo "Year $today, and $count items here"Year 2026, and 4 items hereArithmetic#
$(( )) does whole-number arithmetic. Variables do not need $ inside it:
a=17
b=5
echo "$((a + b)) $((a * b)) $((a / b)) $((a % b))"
count=1
((count++))
echo "$count"22 85 3 2
2Division drops the remainder. For decimals, use awk or bc:
awk 'BEGIN {printf "%.2f\n", 17 / 5}'3.40Default values#
These expansions handle missing values:
echo "Port: ${PORT:-8080}"
PORT=3000
echo "Port: ${PORT:-8080}"
echo "${#PORT} digits"Port: 8080
Port: 3000
4 digitsThis is the normal way to give a script's settings a default.
Special variables#
Read-only values#
readonly VERSION="1.0"
VERSION="2.0"
echo "$VERSION"bash: VERSION: readonly variable
1.0Common mistakes#
Practice#
Practice exercise
Given price=250 and qty=3, print Total: 750 using arithmetic, then print the value of DISCOUNT, using 0 if it is not set.
Show solution
price=250
qty=3
echo "Total: $((price * qty))"
echo "Discount: ${DISCOUNT:-0}"Total: 750
Discount: 0Key takeaway#
Next: Conditions with if and case.
Finished this lesson?