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"Deploying checkout version 2.4.1Three rules that trip everyone up at first:
- No spaces around
=.app = checkoutruns a command calledappwith the arguments=andcheckout. - Names use letters, numbers and underscores and cannot start with a number. By convention, scripts use
lower_casefor their own variables andUPPER_CASEfor environment variables likePATHandHOME. - Everything is text. Bash has no separate number type for normal variables;
version=2.4.1is just a string.
$ app = checkoutapp: command not foundBraces: ${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"prod_dbThe 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"Report for 2026-11-29: 4 entries in /etc/hostsYou 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 $countTotal CPUs: 121Bash arithmetic is integers only. $((7 / 2)) gives 3. For decimals use bc or awk:
echo "scale=2; 7/2" | bcThe 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.
| Quoting | Variables expanded? | Split on spaces? | Globs like * expanded? |
|---|---|---|---|
none: $x | yes | yes | yes |
double: "$x" | yes | no | no |
single: '$x' | no | no | no |
See the difference:
msg="two spaces here"echo $msgecho "$msg"echo '$msg'two spaces heretwo spaces here$msgUnquoted, 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"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 firstQuoting 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"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\""Cost is $20 and the file is "report.txt"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.shregion is: <not set>region is: ap-south-1You can also set a variable for one command only, without changing your shell:
region=us-east-1 ./show-region.shUseful 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'"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}/"Uploading checkout-2.4.1-20261129.tar.gz to s3://releases/checkout/Common mistakes
- Spaces around
=:name = valueis a command, not an assignment. - Unquoted variables:
cp $src $dstbreaks the moment a path contains a space. Writecp "$src" "$dst". - Single quotes when you wanted the value:
echo '$HOME'prints$HOME, not your home folder. - Expecting decimals:
$((10 / 3))is3. - Forgetting
export: the variable works in your shell but your script sees nothing.
Practice
- Set
nameto your name andteamtoplatform, then print a greeting likeHello Leela from the platform teamusing oneechowith double quotes. - Store the number of lines in
/etc/passwdin a variable using$( )andwc -l <, then print it. - Set
file="my notes.txt", runtouch "$file", then comparels $fileandls "$file". Explain the error. - 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 deleteKey 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.
exportmakes a variable visible to scripts and programs you start.