0
0
Bash-scriptingHow-ToBeginner · 3 min read

How to Use echo in Bash: Syntax and Examples

In bash, use the echo command to print text or variables to the terminal. Simply type echo followed by the text or variable you want to display, like echo "Hello, world!".
📐

Syntax

The basic syntax of the echo command is:

  • echo [options] [string]

Here, string is the text or variable you want to print. Options can modify the output, like -n to avoid a new line.

bash
echo [options] [string]
💻

Example

This example shows how to print a simple message and a variable value using echo.

bash
name="Alice"
echo "Hello, world!"
echo "My name is $name"
Output
Hello, world! My name is Alice
⚠️

Common Pitfalls

Common mistakes include forgetting quotes around strings with spaces, which can cause unexpected output or errors. Also, using echo without quotes can lead to word splitting or globbing.

Another pitfall is expecting echo to interpret escape sequences like \n by default; you need to use -e option for that.

bash
echo Hello world  # prints: Hello world

echo "Hello world"  # correct way

echo "Line1\nLine2"  # prints literal \n

echo -e "Line1\nLine2"  # prints with new line
Output
Hello world Hello world Line1\nLine2 Line1 Line2
📊

Quick Reference

OptionDescription
-nDo not output the trailing newline
-eEnable interpretation of backslash escapes
-EDisable interpretation of backslash escapes (default)

Key Takeaways

Use echo to print text or variables to the terminal in bash.
Always quote strings with spaces to avoid unexpected behavior.
Use -e option to enable escape sequences like new lines.
Use -n to print without a trailing newline.
Avoid unquoted variables to prevent word splitting and globbing.