010-160 · Question #64
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. In a bash for loop, echo -n suppresses the trailing newline after each iteration, causing all values to print concatenated on a single line.
Question
Options
- Aanbcn
- Babc
- C$token$token$token
- D(a)(b)(c)
- Ea b c
How the community answered
(55 responses)- A2% (1)
- B73% (40)
- C4% (2)
- D16% (9)
- E5% (3)
Why each option
In a bash for loop, echo -n suppresses the trailing newline after each iteration, causing all values to print concatenated on a single line.
anbcn implies the letter 'n' is inserted between values, but -n is a flag that suppresses newlines - it does not emit any characters of its own into the output stream.
The loop iterates over tokens a, b, and c, assigning each to the variable token in turn. The -n flag passed to echo suppresses the newline that would normally follow each printed value, so a, b, and c are printed back-to-back with no separators, producing 'abc'. The question intends $token as a variable reference; $(token) in the original attempts command substitution but the intended behavior and exam answer reflect $token usage.
$token$token$token would only appear if the literal string '$token' were echoed without variable expansion, which does not occur in standard bash with an unquoted or double-quoted reference.
(a)(b)(c) would require the echo command to explicitly wrap each value in parentheses, which nothing in the loop command does.
a b c with spaces would require a space separator between values, but echo with -n removes newlines and no separator is present, so the values concatenate directly without whitespace.
Concept tested: Bash for loop output with echo -n newline suppression
Source: https://www.gnu.org/software/bash/manual/bash.html#Bash-Builtins
Topics
Community Discussion
No community discussion yet for this question.