← Linux and the Command Line Lesson 37 of 51 · 10 XP

Output: echo and printf

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

echo is handy for simple text, but for formatted output, scripts use printf. It works as in C and behaves the same in all shells:

printf "Hello, %s!\n" "Kai"            # %s — a string
printf "%d + %d = %d\n" 2 3 5          # %d — an integer
printf "%.2f\n" 3.14159                # 3.14
printf "%-10s|%5s|\n" "left" "right"   # alignment: left      |right|
printf "%s\n" a b c                    # the template repeats for each argument

Unlike echo, printf doesn't add a line break by itself: you have to write \n explicitly.

Why not always echo? Different shells understand -e, -n and backslashes differently. In bash echo "a\nb" prints a\nb, while in dash it prints two lines. printf is the same everywhere.

Task. The script gets lines of item price as its input (separated by a space, with the names in plain ASCII letters: printf counts the field width in bytes, and an accented or a Cyrillic letter takes two). Print a neat table: the name aligned to the left in a field 10 wide, then the price with two decimal places in a field 8 wide.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.