01 / GETTING STARTED · LESSON 04

Quoting and command substitution

Preserve argument boundaries while capturing a command’s output.

13 min · learn at your pace

Quotes preserve meaning

Single quotes preserve literal text. Double quotes allow variable and command substitution while keeping the result in one argument. An unquoted expansion can undergo word splitting and filename expansion. A value containing * must stay data unless you deliberately want a glob.

$(command) captures standard output and removes trailing newlines. It does not capture standard error. Prefer this syntax to backticks: it is easier to read and nest. Assignment itself avoids ordinary word splitting, but expansions used later still need quotes.

Values are not programs

Use a constant printf format: printf '%s\n' "$message". Treating the message as the format gives percent signs another meaning. Likewise, a string containing shell punctuation is still a value when quoted; do not run it through eval to manufacture commands.

The practice file has spaces, wildcard characters and percent signs. Keeping these intact demonstrates the difference between one argument containing text and several arguments selected by the shell. This pattern is useful whenever a filename or a human label comes from a file.

Try an example.sh
name=$(cat 'display name.txt')
printf 'Hello, %s!\n' "$name"
YOUR TURN

Put it into practice.

Read `display name.txt` using command substitution. Print exactly `Hello, <file text>!` followed by a newline. Trailing newlines in the file should be removed by substitution; spaces, `*`, `%` and Unicode must remain literal.

See an explained solution
One way to solve it.sh
name=$(cat 'display name.txt') || exit 1
printf 'Hello, %s!\n' "$name"

Command substitution trims the trailing newline. Double quotes then carry the remaining label into printf as one data argument.