Bash Variables: Declaration and Usage

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 34 of 205

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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Bash Variables: Declaration and Usage and get answers drawn from it.

Signed-in readers only.