Bash Variables
Bash variables store text, numbers, or command output so a script can reuse and manipulate data without hard-coding it.
What Is a Bash Variable?
A Bash variable is a named container for a value. Variables have no fixed type -- Bash treats every value as a string unless you use it in an arithmetic context -- and names are case-sensitive, so count and Count are different variables. Names may contain letters, digits, and underscores, but cannot start with a digit. You assign a value with name=value, and there must be no spaces around the equals sign, since Bash would otherwise try to run name as a command.
Example
#!/bin/bash
name="Alice"
age=30
city=Boston
echo "Name: $name"
echo "Age: $age"
echo "City: $city"Reading Variables with $ and Curly Braces
To read a variable's value, prefix its name with a dollar sign: $name. When you need to place a variable next to other text with no separator, wrap the name in curly braces, ${name}, so Bash knows exactly where the variable name ends. Curly braces are also required for array indexing and parameter expansion features like default values.
Example
#!/bin/bash
fruit="apple"
count=3
echo "I have a $fruit"
echo "I have ${count}${fruit}s in my basket"
echo "Default if unset: ${missing:-none}"Quoting Rules: Double, Single, and No Quotes
Quoting controls how Bash expands a variable before using it. Double quotes still expand variables and command substitutions but preserve spaces and prevent word splitting. Single quotes disable all expansion, so the text is used exactly as written. Leaving a variable unquoted lets Bash split it on whitespace and expand any glob characters it contains, which is rarely what you want.
- "$var" expands the variable and keeps spaces and newlines intact
- '$var' is literal text, no expansion at all
- $var unquoted expands, then splits on whitespace and matches globs
- Quote every variable that might hold a path, filename, or user input
Example
#!/bin/bash
path="/home/alice/My Documents"
echo $path
echo "$path"
echo 'The variable is called $path'Exercise: Bash Variables
How do you retrieve the value stored in a variable called `name`?