010-150 · Question #68
What is the output of the following command? for token in a b c; do echo -n ${token}; done
The correct answer is B. abc. The echo -n flag suppresses the trailing newline after each print, so looping over three tokens and printing each without a newline concatenates them into a single unspaced string.
Question
What is the output of the following command? for token in a b c; do echo -n ${token}; done
Options
- Aanbncn
- Babc
- C$token$token$token
- D{a}{b}{c}
- Ea b c
How the community answered
(38 responses)- A11% (4)
- B82% (31)
- C5% (2)
- E3% (1)
Why each option
The echo -n flag suppresses the trailing newline after each print, so looping over three tokens and printing each without a newline concatenates them into a single unspaced string.
anbncn would only occur if the literal character 'n' were being output between values, but -n is an option flag consumed by echo to suppress newlines rather than a character that gets printed.
In each iteration of the loop, echo -n prints the current value of $token without appending a newline character. The three iterations print 'a', 'b', and 'c' consecutively with no separating whitespace or newlines, producing the single output string 'abc'.
$token$token$token would only appear if variable expansion were suppressed (e.g., inside single quotes), but bash expands $token to its current value on each iteration.
{a}{b}{c} would only appear if the variable reference were written with unrecognized brace syntax that bash left unexpanded, but both $token and ${token} are valid and bash expands them normally.
a b c with spaces would require either spaces being printed explicitly between values or separate echo calls that each append a newline; -n removes newlines and no space is ever printed.
Concept tested: Bash for loop output with echo -n newline suppression
Source: https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
Topics
Community Discussion
No community discussion yet for this question.