← Back to Bash Course | Chapter 1: Setup & Basics | Lesson 10 of 12

echo and printf

echo and printf are the two main ways a Bash script displays text on the screen, with printf giving you much more precise control over formatting.

Basic echo

echo is the simplest way to print text: it writes its arguments to standard output separated by single spaces and adds a trailing newline. Multiple arguments are joined with a single space regardless of how many spaces separated them in the source.

Example: Basic echo

bash
#!/bin/bash
echo "Hello, Bash!"
echo Hello    Bash

echo Flags: -n and -e

echo -n prints text without the trailing newline, useful when you want to build a line piece by piece. echo -e turns on interpretation of backslash escape sequences such as \n (newline) and \t (tab), which are otherwise printed literally.

Warning: Plain echo "a\nb" (without -e) prints the literal characters \n, not an actual newline.

Example: echo Flags: -n and -e

bash
#!/bin/bash
echo -n "No newline here... "
echo "and this continues on the same line"
echo -e "Column1\tColumn2\nRow2Col1\tRow2Col2"

printf Basics

printf takes a format string as its first argument and substitutes remaining arguments into placeholders like %s (string) or %d (integer). Unlike echo, it never appends a newline automatically, so you write \n explicitly wherever you want one.

Example: printf Basics

bash
#!/bin/bash
printf "Name: %s, Age: %d\n" "Ada" 36
printf "Pi is roughly %.2f\n" 3.14159

printf for Repeated/Formatted Output

printf recycles its format string over extra arguments if you give it more values than placeholders, which is handy for printing lists in a consistent format without a loop. This also makes printf more predictable than echo when the data being printed might contain special characters.

Example: printf for Repeated/Formatted Output

bash
#!/bin/bash
printf "Item: %s\n" apple banana cherry
Common Mistakes
  1. Assuming echo behaves identically everywhere; its handling of backslash escapes and flags like -e differs between shells and even between Bash versions/builtins vs /bin/echo.
  2. Forgetting that printf does NOT automatically add a newline, unlike echo, so output from consecutive printf calls can run together on one line.
  3. Using echo to print user-controlled or variable data that might start with a dash (like -n), which echo can misinterpret as a flag instead of text.
Chapter Summary
  • echo prints its arguments followed by a newline by default.
  • echo -n suppresses the trailing newline; echo -e enables interpretation of backslash escapes like \n and \t.
  • printf never adds a newline automatically -- you must include \n yourself in the format string.
  • printf supports format specifiers like %s, %d, and %.2f, similar to C's printf, giving precise control that echo lacks.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.