Skip to content
$ lynuxpro
← Bash Scripting

LESSON 2 OF 17 · BEGINNER · 16 MIN

Variables and quoting

HOW IT WORKSHow quoting changes what a command receives

Your lineecho $msg"double"expands $varsunquotedexpands + splits'single'nothing expands1 argument"two spaces"2 argumentstwo | spacesliteral text$msg
1/5

A variable is a name for a value. No spaces around =, and read it back with $.

msg="two  spaces"
echo "$msg"

Variables let a script remember values: an app name, a version, a path, the output of a command. Quoting decides how Bash treats those values when it builds a command. Most real-world Bash bugs, including some that deleted the wrong files in production, come down to a missing pair of quotes. This lesson makes the rules simple.

In simple words

  • Variable: a name that holds a value, such as name=leela. Read it back with $name.
  • Command substitution: $(command) puts a command's output into a variable or another command.
  • Quoting: double quotes keep a value as one piece but still expand variables. Single quotes keep text exactly as written.
  • Environment variable: a variable passed down to programs the script starts. Created with export.

Creating and using variables

Assign with name=value and read with $name:

app=checkoutversion=2.4.1echo "Deploying $app version $version"
SHELLbashutf-8 · 3L
Deploying checkout version 2.4.1
OUTPUTterminalutf-8 · 1L

Three rules that trip everyone up at first:

  • No spaces around =. app = checkout runs a command called app with the arguments = and checkout.
  • Names use letters, numbers and underscores and cannot start with a number. By convention, scripts use lower_case for their own variables and UPPER_CASE for environment variables like PATH and HOME.
  • Everything is text. Bash has no separate number type for normal variables; version=2.4.1 is just a string.
$ app = checkoutapp: command not found
SHELLbashutf-8 · 2L

Braces: ${name}

${name} is the full form of $name. You need it when the variable is followed by characters that could be part of a name:

env=prodecho "$env_db"echo "${env}_db"
SHELLbashutf-8 · 3L
prod_db
OUTPUTterminalutf-8 · 2L

The first line printed nothing, because Bash looked for a variable called env_db, which does not exist. Braces mark exactly where the name ends.

Command substitution: $(command)

$(command) runs a command and replaces itself with the command's output. It is how scripts capture information:

today=$(date +%F)hosts=$(wc -l < /etc/hosts)echo "Report for $today: $hosts entries in /etc/hosts"
SHELLbashutf-8 · 3L
Report for 2026-11-29: 4 entries in /etc/hosts
OUTPUTterminalutf-8 · 1L

You may see the older backtick form `date` in old scripts. It does the same thing but is harder to read and to nest. Use $( ).

Arithmetic: $(( ))

For whole-number maths, use $(( expression )). Inside it you can leave out the $ on variable names:

cpus=4replicas=3echo "Total CPUs: $((cpus * replicas))"count=0count=$((count + 1))echo $count
SHELLbashutf-8 · 6L
Total CPUs: 121
OUTPUTterminalutf-8 · 2L

Bash arithmetic is integers only. $((7 / 2)) gives 3. For decimals use bc or awk:

echo "scale=2; 7/2" | bc
SHELLbashutf-8 · 1L

The three kinds of quoting

This is the most important section of the lesson. When Bash builds a command it goes through the words you typed and expands them. Quotes control that expansion.

QuotingVariables expanded?Split on spaces?Globs like * expanded?
none: $xyesyesyes
double: "$x"yesnono
single: '$x'nonono

See the difference:

msg="two   spaces   here"echo $msgecho "$msg"echo '$msg'
SHELLbashutf-8 · 4L
two spaces heretwo   spaces   here$msg
OUTPUTterminalutf-8 · 3L

Unquoted, Bash split the value into three separate words, and echo printed them with single spaces. Quoted, the value stayed one argument, untouched. In single quotes nothing was expanded at all.

Why unquoted variables are dangerous

Splitting does not just change spacing. It changes how many arguments a command receives. Picture a cleanup script:

file="old report.txt"rm $file      # rm receives TWO arguments: "old" and "report.txt"rm "$file"    # rm receives ONE argument: "old report.txt"
SHELLbashutf-8 · 3L

The unquoted version tries to delete a file called old and a file called report.txt, neither of which you meant. Worse, if a variable is empty and unquoted, it disappears completely:

dir=""rm -rf $dir/*     # becomes: rm -rf /*   — disasterrm -rf "$dir"/*   # becomes: rm -rf /*   — still bad; check the value first
SHELLbashutf-8 · 3L

Quoting prevents the splitting problem; checking values (which you will learn in the error-handling lesson with set -u and ${dir:?}) prevents the empty-value problem.

The rule: always put variables in double quotes, "$var", unless you have a specific reason not to.

Single quotes for literal text

Use single quotes when you want the text exactly as written, such as a pattern for grep or a program for awk that contains $:

echo 'Price: $5 (no variables here)'grep '\$' /etc/hosts || echo "no dollar signs in /etc/hosts"
SHELLbashutf-8 · 2L

Need a single quote inside? End the quotes, add an escaped quote, and start again: 'It'\''s done'. Or simply use double quotes: "It's done".

Escaping single characters

A backslash turns off the special meaning of the next character:

echo "Cost is \$20 and the file is \"report.txt\""
SHELLbashutf-8 · 1L
Cost is $20 and the file is "report.txt"
OUTPUTterminalutf-8 · 1L

Environment variables and export

A normal variable exists only in the current shell. Exporting it copies it into the environment of every program you start from that shell, including scripts:

region=ap-south-1printf '#!/usr/bin/env bash\necho "region is: ${region:-<not set>}"\n' > show-region.shchmod +x show-region.sh./show-region.shexport region./show-region.sh
SHELLbashutf-8 · 6L
region is: <not set>region is: ap-south-1
OUTPUTterminalutf-8 · 2L

You can also set a variable for one command only, without changing your shell:

region=us-east-1 ./show-region.sh
SHELLbashutf-8 · 1L

Useful built-in environment variables include $HOME, $USER, $PATH, $PWD, $HOSTNAME and $RANDOM (a random number from 0 to 32767). See them all with env.

Read-only and unset

readonly MAX_RETRIES=3unset versionecho "version is now: '$version'"
SHELLbashutf-8 · 3L

readonly stops a constant from being changed by accident later in a long script. unset deletes a variable.

Real-world scenario: a versioned artifact name

A release script builds the file name of an artifact from several pieces. Quoting and braces make it safe and readable:

app=checkoutversion=2.4.1build=$(date +%Y%m%d)artifact="${app}-${version}-${build}.tar.gz"echo "Uploading $artifact to s3://releases/${app}/"
SHELLbashutf-8 · 5L
Uploading checkout-2.4.1-20261129.tar.gz to s3://releases/checkout/
OUTPUTterminalutf-8 · 1L

Common mistakes

  • Spaces around =: name = value is a command, not an assignment.
  • Unquoted variables: cp $src $dst breaks the moment a path contains a space. Write cp "$src" "$dst".
  • Single quotes when you wanted the value: echo '$HOME' prints $HOME, not your home folder.
  • Expecting decimals: $((10 / 3)) is 3.
  • Forgetting export: the variable works in your shell but your script sees nothing.

Practice

  1. Set name to your name and team to platform, then print a greeting like Hello Leela from the platform team using one echo with double quotes.
  2. Store the number of lines in /etc/passwd in a variable using $( ) and wc -l <, then print it.
  3. Set file="my notes.txt", run touch "$file", then compare ls $file and ls "$file". Explain the error.
  4. Calculate how many seconds are in a week with $(( )).

Cheat sheet

name=value              assign (no spaces)"$name"  "${name}"      use (always quote)${name}_suffix          braces mark where the name ends$(command)              capture output$((a + b * 2))          integer arithmetic'literal $text'         no expansion\$  \"                  escape one characterexport NAME             pass to child programsVAR=x command           set for one command onlyreadonly NAME=value     constantunset name              delete
OUTPUTterminalutf-8 · 11L

Key takeaways

  • Assign with name=value (no spaces) and read with "$name".
  • $( ) captures command output and $(( )) does integer maths.
  • Double quotes expand variables but keep the value as one argument; single quotes expand nothing.
  • Quote every variable. Unquoted values are split and globbed, which breaks paths with spaces and can delete the wrong files.
  • export makes a variable visible to scripts and programs you start.