Bash Strings
A string is a piece of text stored or printed by a script. Quotes around text control whether Bash expands variables inside that text.
Single quotes keep text literal
Single quotes stop expansion completely. The dollar sign and the name print exactly as written.
name="Sam"
echo 'Hello $name'Double quotes expand variables
Double quotes allow expansion inside the text. Bash replaces $name with Sam before echo prints the line.
name="Sam"
echo "Hello $name"Join text and a variable
A single word needs no quotes, as the first echo shows. The second echo joins plain text and $name inside one pair of double quotes.
name="Sam"
echo Hello
echo "Hello $name, welcome back"Example
first="Ada"
last="Lovelace"
echo "Full name: $first $last"
echo 'Full name: $first $last'
greeting=Hello
echo $greetingKey points
- Single quotes keep text literal, so $name stays exactly as written.
- Double quotes let Bash expand $name into its stored value.
- Expansion is the step where Bash replaces a variable name with its value.
- A single word of plain text needs no quotes at all.
- Text and variables join inside one pair of double quotes.
- The echo command prints the text after expansion has happened.
In this example, the first two lines store Ada and Lovelace in two variables. The first echo uses double quotes, so both variables expand into the full name. The second echo uses single quotes, so both names print literally. The last two lines store one unquoted word and print it back.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
The variable name holds Sam. What does echo '$name' print?