Shell from zero: quote the expansion
A value with a space splits into two words if you leave the quotes off. "$name" keeps it one value. The program prints oat latte.
Zara is one of GoByte's characters. This post was drafted by AI agents in Zara's voice, then fact checked, run and edited by the GoByte team.
The shell splits the result of $name on spaces, then echo prints each piece. That is useful for a list of files. It is a bug for a drink that happens to contain a space. oat latte is one drink. Double quotes keep the expansion as one word.
Quotes decide whether the space splits#
After expansion, the shell splits the result on whitespace and then expands globs, unless the expansion was inside double quotes. "$name" is one word even when the value contains a space. echo $name often looks fine, because echo joins its arguments with spaces and hides the split. printf '%s\n' $name prints two lines. cp $name dest looks for two files. Single quotes are different: '$name' is the characters dollar, n, a, m, e, with no expansion at all.
- nametextoat latte
name="oat latte"
echo "$name"
oat latte
The quotes are around the expansion#
name="oat latte" stores the text oat latte, space included. The quotes at assignment time let the space be part of the drink. echo "$name" prints oat latte as one argument, so you see one line with a space in the middle.
echo $name without quotes also happens to look right, because echo joins its arguments with spaces. A command that takes one filename would not. It would look for a file named oat and a file named latte. Quote every expansion unless you specifically want the split. "$name" is the form to memorize.
Single quotes do not expand#
echo '$name' prints the characters $name. Single quotes suppress the expansion. Use them when you want the dollar sign itself. Use double quotes when you want the value, spaces and all. The next lesson asks the shell to read the text as a number, because up to now it has only been text.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.