Chapter 2 · Lesson 2
Beginner
1 min read
Variables and Quoting
Overview
Shell variables change text before a command runs. Quoting controls whether Bash expands variables and patterns, and whether whitespace splits one argument into several.
Detailed Notes
Assign variables
bash
name="Linux Learner"
count=3
echo "$name"
printf '%s %s
' "$name" "$count"
Do not write spaces around = in assignments:
bash
name = "Linux" # wrong
The shell would interpret name as a command.
Three quoting behaviors
| Syntax | Variable expansion | Pattern expansion | Command substitution |
|---|---|---|---|
"${name}" | Yes | No | Yes |
'${name}' | No | No | No |
unquoted | Yes | Yes | Yes |
bash
name="Linux Learner"
echo "$name"
echo '$name'
echo $name
The quoted form produces one argument containing a space. The unquoted form may split into two arguments.
Command substitution
bash
today="$(date +%F)"
file_count="$(find . -type f | wc -l)"
echo "$today has $file_count files"
$(COMMAND) replaces the text with command output. Double quotes preserve the output as a single variable value in name="$(...)".
Practice
Create a variable for a backup directory, quote it and print both the full path and file count.
Common Interview Questions
Finished this lesson?
0 of 25 lessons done · 0% of the course

