Bash Variables: Declaration and Usage
A variable is a named place in memory where a script keeps a value so that it can use the value again later. Instead of typing the same file name, number, or message in ten places, you store it once under a name and refer to the name. If the value changes, you change it in one spot.
In Bash, variables are simple. There is no separate declaration step and no required type: a variable begins to exist the moment you assign a value to it.
Assigning a Value
The syntax of an assignment is the variable name, an equals sign, and the value, with no spaces on either side of the equals sign:
name="Asha"
age=30
The first line stores the text Asha in a variable called name, and the second stores 30 in age. Quotes around a value are needed only when it contains spaces or special characters, but using them is a safe habit.
The strict spacing rule exists because Bash decides what a line means by looking at its first word. name="Asha" is one word that contains an equals sign, so Bash recognizes it as an assignment. If you add spaces, the line becomes a command followed by arguments, and Bash tries to run a program with that name. Each of the following lines fails in a different way:
count = 5
count= 5
count =5
count: command not found
5: command not found
count: command not found
The first and third lines tried to run a command called count. The second line is more subtle: count= sets count to an empty value only for the duration of a command named 5, which does not exist. In all three cases, the cause is the same stray space.
Using a Variable
To read a variable, put a dollar sign in front of its name. Bash replaces $name with the stored value before it runs the command, a step known as expansion:
name="Asha"
age=30
echo "Name: $name, Age: $age"
Name: Asha, Age: 30
Notice that the dollar sign is used only when reading. When assigning, you write name=, without it. A common beginner mistake is to put a dollar sign on the left side of an assignment:
x=1
$x=2
1=2: command not found
Bash expanded $x to 1 first, and then tried to run a command called 1=2.
Using Braces to Mark the End of a Name
Bash reads a variable name for as long as it sees letters, digits, and underscores. Sometimes you want to attach text directly to a value. Curly braces show where the name ends:
name="Asha"
echo "${name}s book"
echo "$names book"
Ashas book
book
The first line used ${name} and printed the value followed by the letter s. The second line asked for a variable called names, which does not exist, so it expanded to nothing. The braces are optional when no ambiguity exists, but they are always allowed, and they are required for the more advanced expansions that later lessons cover.
Quotes Control Expansion
The kind of quotes you use decides whether Bash expands variables inside a string:
name="Asha"
greeting="Hello, $name"
single='Hello, $name'
echo "$greeting"
echo "$single"
Hello, Asha
Hello, $name
Double quotes allow expansion, while single quotes keep every character exactly as written. To print a literal dollar sign inside double quotes, put a backslash in front of it:
price=5
echo "Cost: \$$price"
Cost: $5
A full lesson on quoting comes later in this tutorial. For now, remember to put double quotes around variable expansions, as in "$name". The reason is clear in this example, where a value contains a space:
file="my notes.txt"
printf '[%s]\n' $file
printf '[%s]\n' "$file"
[my]
[notes.txt]
[my notes.txt]
Without quotes, Bash splits the value at the space and passes two separate arguments. With quotes, it stays one argument. This behavior is called word splitting, and it causes many hard-to-find bugs.
A related problem occurs when you assign a value that has spaces and forget the quotes:
msg=hello world
world: command not found
Bash read this as "run the command world with msg=hello set for that command only". Writing msg="hello world" fixes it.
Variables Hold Text
Every Bash variable stores text, even when the text looks like a number. Putting 7 into a variable does not make it a number. To do arithmetic, use arithmetic expansion, written $(( ... )), which treats the text inside as a mathematical expression:
x=7
y=3
echo $((x + y)) $((x * y)) $((x / y)) $((x % y))
z=$((x + y))
echo "z=$z"
echo "string add: $x+$y"
10 21 2 1
z=10
string add: 7+3
The four results are the sum, product, quotient, and remainder. The division is integer division, so 7 / 3 gives 2, and % gives the remainder, 1. Inside $(( )) you can write variable names without the dollar sign. The last line shows that plain text expansion does no math: it just prints 7+3. A later lesson covers arithmetic expansion in full.
Joining and Appending Text
Putting two expansions side by side joins them, and += appends to an existing value:
a="foo"
b="bar"
c="$a$b"
echo "$c"
c+="-baz"
echo "$c"
foobar
foobar-baz
Because values are text, += on a variable that holds a number appends characters by default instead of adding:
n=5
n+=3
echo "n=$n"
n=53
If you want += to add numerically, declare the variable as an integer first with declare -i:
declare -i m=5
m+=3
echo "m=$m"
declare -i t="2+3"
echo "t=$t"
m=8
t=5
The -i attribute tells Bash to evaluate the assigned value as arithmetic every time. The second example shows that even the text 2+3 is calculated when the attribute is set.
A leading zero has a special meaning in arithmetic: Bash treats a number that starts with 0 as octal (base 8). So 010 is eight, not ten. To force decimal, give the base explicitly with 10#:
num=010
echo "num=$num, arithmetic: $((num))"
echo $((10#010))
num=010, arithmetic: 8
10
Storing the Output of a Command
Command substitution, $(command), runs a command and replaces itself with the text it printed. Combined with an assignment, this captures the output into a variable:
year=$(date +%Y)
lines=$(printf 'a\nb\nc\n' | wc -l)
echo "Year: $year"
echo "Lines: $lines"
Year: 2026
Lines: 3
The year depends on the day you run the example. Command substitution is the subject of its own lesson later in the course.
Several Assignments on One Line
You can put several assignments on the same line, separated by spaces:
p=1 q=2 r=3
echo "$p $q $r"
1 2 3
A Temporary Value for One Command
When assignments appear before a command, they last only for that command and do not change the variable in the current shell. The mechanism is how scripts pass settings to a program without altering their own state:
temp=outer
temp=inner bash -c 'echo "inside: $temp"'
echo "after: $temp"
inside: inner
after: outer
The child bash saw temp as inner, but the original value was left alone.
Unset and Empty Variables
A variable that was never assigned expands to an empty string, and Bash does not report an error:
echo "[$undefined_var]"
[]
This silent behavior makes a misspelled variable name hard to notice. The shell option set -u makes Bash stop with an error instead, which is covered in the lessons on strict mode:
set -u
echo "$nothing_here"
echo after
nothing_here: unbound variable
The script stopped at the first line, so after was never printed.
A variable that is set to an empty string is different from one that does not exist at all. The expansion ${var+word} yields word only when the variable is set, even to an empty value, and so it can tell the two cases apart:
empty=""
echo "empty is set: ${empty+yes}"
echo "undefined is set: ${undefined_var+yes}"
empty is set: yes
undefined is set:
Finding the Length of a Value
The expression ${#variable} returns the number of characters in the value:
word="banana"
echo "${#word}"
6
Inspecting Variables with declare -p
The built-in declare -p prints the definition of a variable, including its attributes. It shows what is really stored, which is useful when debugging:
name="Asha"
age=30
declare -p name age
declare -- name="Asha"
declare -- age="30"
The double dash means that the variables have no special attributes. Both values appear in quotes, which confirms that the number 30 is stored as text. A variable declared with declare -i would show an i flag instead of the dashes.
Changing a Value
Assigning to an existing variable replaces its old value:
name="Asha"
name="Ravi"
echo "$name"
Ravi
The next lessons cover how to choose variable names, how variables reach other programs through the environment, and how to make a value read-only.