Ravindra BagaleCourses & study guides मराठी Track your progress

AWS Cloud

Shell Scripting Complete 2: Bash Variables, Quoting, Command Substitution and Parameter Expansion

Variables let a script remember things: a file name, a date, a count. Quoting decides whether bash treats spaces and stars as text or as special characters, and it is the number one cause of script bugs. Command substitution puts the output of one command into a variable. This chapter teaches all three step by step, plus default values, string tricks, arithmetic, environment variables and the special variables like $0 and $$.

In this chapter

  • Create and use variables correctly
  • Know single quotes, double quotes and no quotes
  • Capture command output with $( )
  • Use defaults and string operations
  • Do integer maths with $(( ))
  • Export environment variables

1. An everyday example: labelled jars in the kitchen

In a kitchen every jar has a label: sugar, salt, tea. When the recipe says 'add sugar' you pick the jar by its label and use what is inside. If someone puts salt in the sugar jar, the tea tastes bad. Variables are labelled jars, and quoting is the lid that keeps the contents as they are.

Jar label = variable name. What is inside = value. Taking from the jar = $name. Lid closed = "$name" (contents stay whole). Filling a jar from a machine = name=$(command). Sharing the jar with neighbours = export.

How bash expands a lineReads the lineReplaces $name and $(cmd)Splits unquoted results on spacesExpands * and ? in unquoted wordsRemoves the quotesRuns the command
Double quotes stop steps 3 and 4.

2. Create a variable: name=value

A script that repeats the same path ten times is hard to change. Put it in one variable and change it in one place.

Write name=value with no spaces around =. Names use letters, digits and _ and cannot start with a digit. Read it with $name or ${name}. Use lower case for your own variables; UPPER case is used by the system (PATH, HOME). unset name deletes it. readonly name makes it constant.

  1. Set and print.
city=Pune; echo "I live in $city"

Output:

I live in Pune

$city was replaced by its value.

  1. Spaces break it.
city = Pune

Output:

bash: city: command not found

bash thought city was a command.

  1. Braces join text.
f=report; echo "${f}_2026.csv"

Output:

report_2026.csv

Without braces bash looks for a variable called f_2026.

  1. Constant.
readonly TAX=18; TAX=20

Output:

bash: TAX: readonly variable

It cannot be changed.

3. Double quotes: keep spaces, still expand

Bash turns a command line into separate arguments. A filename such as April report.txt is one name even though it has a space. Store it in file and compare printing $file with printing "$file" using a format like printf '[%s]\n'. In the unquoted call, the space can split the value into two arguments. Double quotes keep the expanded value together. This is why a command that worked with report.txt may fail when a real user supplies a filename containing spaces.

File names and user input often have spaces. Without quotes one name becomes two arguments and the command breaks.

Inside "double quotes" bash still replaces $var, $(cmd) and $((math)), but it does not split on spaces and does not expand * or ?. Rule: always write "$var" unless you have a reason not to. Use \" for a quote inside and \$ for a literal dollar.

  1. A name with a space.
f='Sales Q3.xlsx'; ls -l $f

Output:

ls: cannot access 'Sales': No such file or directory
ls: cannot access 'Q3.xlsx': No such file or directory

Unquoted: split into two words.

  1. Quoted.
ls -l "$f"

Output:

-rw-r--r-- 1 asha asha 20480 Oct 25 11:00 Sales Q3.xlsx

One argument, it works.

  1. Star stays a star.
p='*.log'; echo "$p"

Output:

*.log

Inside quotes * is not expanded.

  1. Escape inside.
echo "Price: \$5 for \"chai\""

Output:

Price: $5 for "chai"

Backslash keeps $ and " as text.

4. Single quotes: everything is plain text

Sometimes you want $ and * printed exactly, for example in awk programs, regex or a message about $HOME.

Inside 'single quotes' nothing is special: no $var, no $( ), no \. You cannot put a single quote inside single quotes; close and reopen: 'it'\''s'. Use single quotes for fixed text and double quotes when you need a variable. $'...' is a third form that understands \n and \t.

Form$var expands?Spaces kept?
no quotesYesNo, split
"double"YesYes
'single'NoYes
$'ansi'No, but \n worksYes
  1. Compare.
echo "Home is $HOME"; echo 'Home is $HOME'

Output:

Home is /home/asha
Home is $HOME

Single quotes print it literally.

  1. awk needs single quotes.
awk -F: '{print $1}' /etc/passwd | head -2

Output:

root
bin

$1 belongs to awk, not to bash.

  1. A quote inside.
echo 'Ravi'\''s laptop'

Output:

Ravi's laptop

Close, escaped quote, reopen.

  1. ANSI form.
echo $'line1\nline2'

Output:

line1
line2

\n became a new line.

5. Command substitution: $(command)

Command substitution runs a command and places its standard output where the expression appeared. For example, stamp=$(date +%F) takes the date printed by date and stores it in a variable you can use in a backup filename. Bash removes trailing newlines from the captured value. Try writing the stamp inside square brackets with printf to see exactly what you received. If the command fails, check its status before using the value to build a path.

Scripts often need today's date, the server name or a count of files inside a message or a file name.

$(command) runs the command and puts its output in its place, with the final new line removed. Old style is `command` with backticks; prefer $( ) because it nests and is easy to read. Quote it: "$(command)" keeps spaces and new lines.

  1. Date in a file name.
today=$(date +%F); echo "backup-$today.tgz"

Output:

backup-2026-10-25.tgz

The date command ran first.

  1. Count lines.
users=$(wc -l < /etc/passwd); echo "$users accounts"

Output:

38 accounts

< gives wc the file without printing its name.

  1. Nesting.
echo "Kernel dir: $(basename $(dirname /lib/modules/$(uname -r)/kernel))"

Output:

Kernel dir: 6.1.0-18-amd64

$( ) inside $( ) is easy to read.

  1. Keep new lines.
top3=$(ls /etc | head -3); echo "$top3"

Output:

adduser.conf
alternatives
apt

Quoted output keeps each name on its own line.

6. Default values and checks: ${var:-x} and friends

Test two states: a variable that has never been set and a variable assigned an empty string. ${dir:-lab} gives the fallback in either case, while ${dir-lab} only does so if the variable is unset. Print the value surrounded by brackets in both experiments. Seeing [] confirms you got an empty value. Use a fallback where the default makes sense. For a required input such as an export folder, stop and explain which value the student must provide.

Scripts must behave well when a value is missing, for example when the user forgets an argument.

${var:-default} gives default if var is empty or unset (var is not changed). ${var:=default} also stores it. ${var:?message} stops the script with the message if it is empty. ${var:+other} gives other only when var has a value. These work well with set -u.

FormIf var is emptyIf var is set
${var:-d}gives dgives var
${var:=d}sets var=dgives var
${var:?msg}error and stopgives var
${var:+x}gives emptygives x
  1. Default port.
echo "port ${PORT:-8080}"

Output:

port 8080

PORT was not set, so 8080 was used.

  1. Set and keep.
: "${ENVNAME:=dev}"; echo $ENVNAME

Output:

dev

The : command does nothing, but the expansion stores dev.

  1. Required.
bash -c 'echo "${DB_HOST:?set DB_HOST first}"'

Output:

bash: line 1: DB_HOST: set DB_HOST first

The script stops with a clear message.

7. String tricks: length, cut, replace, case

Renaming files, removing extensions and cleaning input are daily jobs. Bash can do them without calling sed or awk.

${#v} length. ${v#pat} removes the shortest match from the start, ${v##pat} the longest. ${v%pat} removes from the end, ${v%%pat} the longest. ${v/old/new} replaces the first, ${v//old/new} all. ${v:start:len} takes a part. ${v^^} upper case, ${v,,} lower case.

FormExample (f=/data/img/photo.big.jpg)Result
${f##*/}file name onlyphoto.big.jpg
${f%/*}folder only/data/img
${f%.*}drop last extension/data/img/photo.big
${f##*.}extension onlyjpg
  1. Length.
pin=411038; echo ${#pin}

Output:

6

Six characters.

  1. Change extension.
f=invoice.docx; echo "${f%.docx}.pdf"

Output:

invoice.pdf

%.docx removed the end.

  1. Replace all.
s='a b c'; echo "${s// /_}"

Output:

a_b_c

Every space became _.

  1. Upper case and substring.
code=mh12ab; echo "${code^^} ${code:0:4}"

Output:

MH12AB mh12

^^ upper, :0:4 first four.

8. Arithmetic: $(( )), (( )) and let

Counters, totals, percentages and retries all need numbers.

$(( expr )) calculates integers: + - * / % and ** (power). Inside you can write names without $. (( count++ )) changes a variable. Division drops decimals: 7/2 is 3. For decimals use bc or awk. Numbers starting with 0 are read as octal (08 fails), so strip zeros or use 10#08.

  1. Add.
a=40; b=2; echo $((a + b))

Output:

42

No $ needed inside.

  1. Counter.
n=0; ((n++)); ((n+=5)); echo $n

Output:

6

(( )) changes the variable.

  1. Percentage.
used=37; total=50; echo "$(( used * 100 / total ))%"

Output:

74%

Multiply first, then divide.

  1. Decimals with bc.
echo 'scale=2; 7/3' | bc

Output:

2.33

Bash itself only does integers.

9. Environment variables and export

Child programs (python, java, another script) only see variables that you export.

A normal variable lives only in the current shell. export name makes it an environment variable that every child process gets. env or printenv lists them. VAR=value command sets it only for that one command. To keep it for every login, add export lines to ~/.bashrc (the environment chapter has details).

  1. Not exported.
color=blue; bash -c 'echo "child sees: $color"'

Output:

child sees:

The child shell got nothing.

  1. Exported.
export color; bash -c 'echo "child sees: $color"'

Output:

child sees: blue

Now it is in the environment.

  1. Only for one command.
TZ=Asia/Tokyo date +%H:%M; date +%H:%M

Output:

14:35
11:05

TZ changed only for the first date.

  1. Find one.
printenv | grep ^LANG

Output:

LANG=en_IN.UTF-8

printenv shows exported variables.

10. Special variables: $0, $$, $!, $?, $RANDOM, $LINENO

Bash fills some variables for you. They are useful for logs, temp files and error messages.

$0 script name. $$ PID of the current shell (good for unique temp names). $! PID of the last background job. $? last exit code. $RANDOM a number 0-32767. $LINENO current line number. $SECONDS seconds since the script started. $1, $#, $@ are arguments; chapter 3 covers them.

VariableHolds
$0script name
$$this shell PID
$!last background PID
$?last exit code
$RANDOMrandom 0-32767
$SECONDSseconds running
  1. Unique temp file.
echo "/tmp/report.$$"

Output:

/tmp/report.48213

Different every run.

  1. Background PID.
sleep 30 & echo "started $!"

Output:

[1] 48250
started 48250

Save $! to wait for or kill it later.

  1. Timer.
bash -c 'sleep 2; echo "took $SECONDS s"'

Output:

took 2 s

Easy timing for scripts.

  1. Safer temp file.
t=$(mktemp); echo "$t"

Output:

/tmp/tmp.Xk29aQ

mktemp makes a random, private file.

11. Real examples from many industries

The same Linux skill shows up in every kind of company. Seeing it in many places helps you remember it.

Each row is a made-up team. It shows who uses this and how.

Team and cityHow they use itCommand
Pooja, travel agency, PuneDates in backup namesbackup-$(date +%F).tgz
Oliver, insurance, ManchesterQuotes for file names with spacescp "$src" "$dst"
Mei, e-commerce, SingaporeDefault ports with ${PORT:-8080}${PORT:-8080}
Ahmed, telecom, RiyadhRename extensions in bulk${f%.txt}.csv
Ana, pharma, LisbonPercent disk used$(( used*100/total ))
Rahul, fintech, MumbaiRequired secrets with :?${API_KEY:?missing}

12. Common errors and how to fix them

Everyone hits these errors. Knowing the cause saves hours.

Read the exact message first. Then match it to a row below.

Error you seeWhy it happensHow to fix
command not found (after name = value)Spaces around =Remove the spaces.
name=value
No such file or directory for a name with spacesVariable not quotedUse double quotes.
ls "$f"
$HOME printed literallySingle quotes usedUse double quotes for expansion.
echo "$HOME"
readonly variableChanging a constantUse another name.
readonly -p
value too great for base (error token is "08")Leading zero = octalForce base 10.
echo $((10#08))
syntax error: invalid arithmetic operator (error token is ".5")Decimals in $(( ))Use bc or awk.
echo '2.5*2' | bc
child script does not see my variableNot exportedexport it.
export name
parameter null or not set${var:?} and var is emptySet the variable first.
export DB_HOST=db1
unexpected EOF while looking for matching quoteA quote is not closedClose every quote.
bash -n s.sh

13. Troubleshooting step by step

Print the variable with markers so you can see spaces and empty values.

Go top to bottom. Stop at the first step that shows the problem.

  1. See the exact value.
echo "[$name]"
  1. Show type and attributes.
declare -p name
  1. Is it exported?
printenv name
  1. Trace expansion.
bash -x s.sh
  1. Find unquoted use.
shellcheck s.sh
  1. Check hidden characters.
printf '%q\n' "$name"

14. Lab 1: A backup name builder

Write a script that builds a safe backup file name from the host, date and a folder, using variables, $( ) and string tricks.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Folder.
mkdir -p ~/lab38 && cd ~/lab38
  1. Variables.
src="/var/www/my site"; host=$(hostname -s); day=$(date +%F)
  1. Build the name.
base=${src##*/}; name="${host}-${base// /_}-${day}.tgz"; echo "$name"

Output:

web01-my_site-2026-10-25.tgz
  1. Length check.
echo ${#name}

Output:

28
  1. Upper case tag.
echo "${host^^}"

Output:

WEB01
  1. Default target folder.
echo "${DEST:-/backup}/$name"

Output:

/backup/web01-my_site-2026-10-25.tgz

15. Lab 2: Quoting experiments and export

See with your own eyes how quotes change the result, and how export passes values to child scripts.

A full hands-on lab. Run every step on a test Linux machine (an EC2 instance, a VM, or WSL).

  1. Make tricky files.
touch 'a b.txt' c.txt && ls

Output:

a b.txt  c.txt
  1. Unquoted loop.
for f in $(ls); do echo "[$f]"; done

Output:

[a]
[b.txt]
[c.txt]
  1. Glob instead.
for f in *.txt; do echo "[$f]"; done

Output:

[a b.txt]
[c.txt]
  1. Child script.
printf '#!/bin/bash\necho "mode=$MODE"\n' | tee child.sh && chmod +x child.sh
  1. Without export.
MODE=prod; ./child.sh

Output:

mode=
  1. With export.
export MODE; ./child.sh

Output:

mode=prod
  1. Maths.
files=$(ls | wc -l); echo "$(( files * 2 )) after copy"

Output:

6 after copy

Ravindra Bagale's Tip

Quote every variable: "$var" and "$(cmd)". If you remember only one rule from this chapter, remember this one. It stops spaces and stars in names from breaking your script or deleting the wrong files.

16. Frequently asked questions

Q. $var or ${var}?

Same; braces are needed when text follows.

Q. Why no spaces around =?

Bash would read the name as a command.

Q. Backticks or $( )?

$( ): nests and reads better.

Q. Can bash do decimals?

No; use bc or awk.

Q. How to see all my variables?

declare -p or set.

Q. Lower or upper case names?

Lower for yours, upper for environment.

Q. What does export -n do?

Removes the export mark.

Q. Is $RANDOM safe for passwords?

No; use openssl rand.

17. Interview questions and answers

Beginner level

Q. How to create a variable?

name=value with no spaces.

Q. Single vs double quotes?

Single: literal. Double: expands variables.

Q. Store a command's output?

x=$(command).

Q. Length of a string?

${#var}.

Mid level level

Q. ${v:-d} vs ${v:=d}?

First only gives d; second also stores it.

Q. Why quote "$var"?

Stop word splitting and globbing.

Q. Remove extension?

${f%.*}.

Q. What does export do?

Passes the variable to child processes.

Senior level

Q. Explain bash expansion order.

Brace, tilde, parameter/command/arithmetic, word split, glob, quote removal.

Q. Why is for f in $(ls) bad?

Splits names on spaces and breaks on special chars; use globs.

Q. Handle 08 in arithmetic?

10#08 or strip leading zeros.

Q. Make a secret required?

${SECRET:?message} with set -u.

Try at home

  1. Write a script that prints your user, the number of files in /etc and the percent of disk used on /.
  2. Take a file name with spaces in a variable and print it once with and once without quotes. Write what changed.

Practise this chapter

Interview questions and answers

A script works on report.txt but fails on April report.txt. What do you check?

Inspect how the filename reaches the command. Unquoted expansion can split a value with spaces into several arguments. Try printing bracketed arguments to verify. Quote the expansion and test the same filename again.

Check your understanding

Choose an answer, then compare your reasoning with the explanation.

0 of 3 answered correctly
1. Which expression expands a variable and keeps its spaces together as one argument?

Answer and explanation

B. "$file"

Double quotes still allow expansion but preserve the resulting value as one argument. Single quotes pass literal text.

2. Where does the value in stamp=$(date +%F) come from?

Answer and explanation

A. Standard output of date with trailing newlines removed

Command substitution captures standard output. Check the assignment’s status separately when success matters.

3. A variable is set to an empty string. What does the colon-dash fallback do?

Answer and explanation

C. Uses the supplied fallback

The colon form treats both unset and null as needing the fallback. It does not assign the value unless you use an assigning form.

Practice Tasks

Practice checks run in your browser. They check the answer for this exercise; they do not create resources or connect to your AWS account.

About this scenario

Vidarbha Cotton Mills is a textiles business in Nagpur. Ganesh Wankhede looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.

0 / 21

Easy Set a variable

Wrong quoting breaks BIZ scripts on file names with spaces.

Store the word Kothrud in a variable named area.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Print with quotes

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the variable branch inside double quotes.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Capture whoami

Wrong quoting breaks BIZ scripts on file names with spaces.

Store the output of whoami in a variable named me.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Length

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the length of the variable mobile.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Upper case

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the variable state in upper case.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Lower case

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the variable CODE in lower case.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Multiply

Wrong quoting breaks BIZ scripts on file names with spaces.

Print 12 times 8 with bash arithmetic.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Easy Export

Wrong quoting breaks BIZ scripts on file names with spaces.

Export the variable APP_ENV with the value qa in one command.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Month in name

Wrong quoting breaks BIZ scripts on file names with spaces.

Store the current year-month like 2026-10 in a variable named ym using date.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Default value

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the variable REGION, or ap-south-1 if it is empty.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Drop extension

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the variable doc without its .odt ending.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium File name only

Wrong quoting breaks BIZ scripts on file names with spaces.

Print only the file name part of the path variable p (after the last slash), using parameter expansion.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Replace all

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the variable title with every space turned into a dash.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium First three

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the first 3 characters of the variable ifsc.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Remainder

Wrong quoting breaks BIZ scripts on file names with spaces.

Print the remainder of 47 divided by 6.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Decimals

Wrong quoting breaks BIZ scripts on file names with spaces.

Use bc to print 22 divided by 7 with 3 decimals.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium For one command

Wrong quoting breaks BIZ scripts on file names with spaces.

Run date with TZ set to Europe/London only for that command.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Medium Constant

Wrong quoting breaks BIZ scripts on file names with spaces.

Make a read-only variable GST with value 0.18.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Required

Wrong quoting breaks BIZ scripts on file names with spaces.

Print TOKEN, but stop with the message "TOKEN missing" if empty.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Leading zero

Wrong quoting breaks BIZ scripts on file names with spaces.

Print 09 plus 1 forcing base ten.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

Hard Temp folder

Wrong quoting breaks BIZ scripts on file names with spaces.

Create a private temporary directory and store its path in tmpd.

  1. Find the Linux command that does this job.
  2. Add the options (like -r or -h) the task needs.
  3. Add the file names, folders or users in the right order.
  4. Use sudo if the job changes system files or users. Click Check answer.

In short

  1. name=value, no spaces; read with $name.
  2. Double quotes expand but keep spaces.
  3. Single quotes keep everything literal.
  4. $(cmd) captures output.
  5. ${v:-d}, ${#v}, ${v%.*} and $(( )) do defaults, length, cuts and maths.
  6. export passes variables to child processes.

Revision, comparison and interview cards

Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.

Quotes in 4 rules. Single quotes: exact text. Double quotes: variables expand. Always quote variables. Example.
Revision card: Quotes in 4 rules · Download PNG · Open card page
Parameter expansion. Default if empty. Length. Cut suffix. Replace.
Revision card: Parameter expansion · Download PNG · Open card page
'single' vs "double". Exact text, no expansion. / $var and $( ) expand.
Comparison: 'single' vs "double" · Download PNG · Open card page
var=x vs export var=x. Only this shell. / This shell and child programs.
Comparison: var=x vs export var=x · Download PNG · Open card page
Single vs double quotes?. Single: nothing expands. Double: $var and $( ) expand. Try.
Interview card: Single vs double quotes? · Download PNG · Open card page
$( ) vs backticks?. Both capture output. $( ) nests and reads better. Example.
Interview card: $( ) vs backticks? · Download PNG · Open card page
Why export a variable?. Plain variables stay in this shell. export passes them to children. Example.
Interview card: Why export a variable? · Download PNG · Open card page
Do math in bash?. Use $(( )) for integers. No decimals in bash. Example.
Interview card: Do math in bash? · Download PNG · Open card page

More cards: Ravi Sir's Cards.