Where to start First steps track · 15 stages
Linux Labs

echo — printing text

3 min bash

Printing strings and variables; -n and -e, escaping, when to prefer printf.

Cheat sheet

5 commands Printable version
  • echo "x=$var" with variable expansion
  • echo 'literal $x' without expansion
  • echo -n / echo -e no trailing \n / with escapes
  • echo "x" >> file append to a file
  • printf '%s\n' "$v" a portable equivalent

Overview

echo prints its arguments to stdout, separated by spaces, with a trailing newline. It's the main tool for "show a value" and "write a line to a file".

bash
echo "Hello"                  # Hello
echo "PATH = $PATH"            # variables expand in "double quotes"
echo 'literal $PATH'           # in 'single quotes' — as-is, no expansion
echo "$USER lives in $HOME"

Options

3
bash
echo -n "no trailing newline"   # -n: don't append \n at the end
echo -e "column1\tcolumn2"      # -e: enable escapes (\t \n \\)
echo "stars: *"                # inside quotes, * is NOT expanded into filenames
echo *                          # WITHOUT quotes — a list of files (globbing!)

Rule of thumb: variables and special characters go in double quotes; fully literal text goes in single quotes. More on expansion — globbing and env-vars.

Option What it does Example
-n Do not append a trailing newline. echo -n "no newline"
-e Enable interpretation of backslash escapes (\n, \t, \\). echo -e "col1\tcol2"
-E Explicitly disable backslash escapes (the default in bash). echo -E "literal\ttext"

Nothing found. Try a shorter query.

Recipes

2

Writing to a file

bash
echo "server { }" > nginx.conf          # create/overwrite
echo "log_level=debug" >> app.conf      # append
printf '%s\n' "line1" "line2" > f    # several lines are more reliable via printf
echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf   # into a protected file (see tee)

When to use printf

echo behaves differently across shells (especially -e/-n). For scripts and exact formatting, use printf — it's portable and predictable:

bash
printf '%s\n' "$var"          # a reliable equivalent of echo "$var"
printf '%b\n' 'a\tb'          # with escape interpretation (like echo -e)

Troubleshooting

3

-e printed as literal text

The shell isn't bash (behavior differs in sh/dash), or echo is an external binary. Use printf instead.

An asterisk turned into a file list

echo * without quotes is subject to globbing. Quote it: echo "*".

The newline isn't where I want it

echo always adds a trailing \n; to skip it, use -n; to insert one in the middle, use -e "...\n..." or printf.

See also

  • printf — Formatted output in the shell — more reliable than echo, formats and escapes.
  • env-vars — env, export, $PATH, ~/.bashrc vs profiles; why "command not found".
  • bash-scripting — Variables, conditionals, loops, arguments, and the safe mode set -euo pipefail.
Loading…