nerdexam
LPI

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.

The Power of the Command Line

Question

What is the output of the following command? for token in a b c; do echo -n $(token); done

Options

  • Aanbcn
  • Babc
  • C$token$token$token
  • D(a)(b)(c)
  • Ea b c

How the community answered

(55 responses)
  • A
    2% (1)
  • B
    73% (40)
  • C
    4% (2)
  • D
    16% (9)
  • E
    5% (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.

Aanbcn

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.

BabcCorrect

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.

C$token$token$token

$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.

D(a)(b)(c)

(a)(b)(c) would require the echo command to explicitly wrap each value in parentheses, which nothing in the loop command does.

Ea b c

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

#for loops#bash scripting#command substitution#echo

Community Discussion

No community discussion yet for this question.

Full 010-160 Practice