nerdexam
LPI

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.

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

  • Aanbncn
  • Babc
  • C$token$token$token
  • D{a}{b}{c}
  • Ea b c

How the community answered

(38 responses)
  • A
    11% (4)
  • B
    82% (31)
  • C
    5% (2)
  • E
    3% (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.

Aanbncn

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.

BabcCorrect

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

C$token$token$token

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

D{a}{b}{c}

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

Ea b c

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

#for loop#shell scripting#echo command#loop output

Community Discussion

No community discussion yet for this question.

Full 010-150 Practice