010-100 · Question #20
What is the output of the following command sequence? for token in a b c; do echo -n "$token "; done
The correct answer is B. a b c. echo -n suppresses the trailing newline, so each token prints on the same line with a space, producing space-separated output concatenated into one line.
Question
What is the output of the following command sequence? for token in a b c; do echo -n "$token "; done
Options
- Aanbncn
- Ba b c
- C"a " "b " "c "
- Dtoken token token
- Eabc
How the community answered
(42 responses)- A2% (1)
- B76% (32)
- C2% (1)
- D14% (6)
- E5% (2)
Why each option
echo -n suppresses the trailing newline, so each token prints on the same line with a space, producing space-separated output concatenated into one line.
anbncn would only appear if -n were treated as a literal character inserted between tokens, which is not how the echo -n flag works.
The for loop iterates over the three tokens a, b, and c; each iteration executes echo -n "$token " which prints the expanded variable value followed by a literal space and no newline. The three outputs concatenate directly on a single line, yielding 'a b c ' with a trailing space - matching choice B as the only option showing space-separated tokens without surrounding quotes or extra characters.
echo does not output surrounding quotation marks - quotes in the script are shell syntax used for grouping and are never printed as literal characters.
token token token would result if $token were not expanded, but double quotes permit variable expansion, so the loop variable's value is substituted on each iteration.
abc would appear only if no space were present inside the quoted argument to echo, but the format string "$token " includes an explicit trailing space.
Concept tested: bash for loop iteration and echo -n output suppression
Source: https://www.gnu.org/software/bash/manual/bash.html#Looping-Constructs
Topics
Community Discussion
No community discussion yet for this question.