Overview
The echo command is one of the most fundamental and frequently used commands in Linux. It displays text, variables, and data to standard output (your terminal) or redirects it to files. Despite its apparent simplicity, echo is a powerful tool for shell scripting, debugging, user interaction, and system automation.
Primary Functions:
- Display text messages to the terminal
- Print shell variable values
- Create simple text files
- Generate formatted output for scripts
- Debug scripts by showing variable values
- Provide user feedback during automation
- Write data to files via redirection
/usr/bin/echo binary. The built-in version is used by default and is much faster. Use type echo to see which you're using.
Common Options
| Option | Description |
|---|---|
| -n | Do not output the trailing newline (cursor stays on same line) |
| -e | Enable interpretation of backslash escape sequences |
| -E | Disable interpretation of backslash escapes (default in most shells) |
Escape Sequences (when using -e)
| Escape | Description |
|---|---|
| \n | Newline (line break) |
| \t | Horizontal tab |
| \r | Carriage return |
| \b | Backspace |
| \a | Alert (bell/beep) |
| \\ | Backslash itself |
| \c | Suppress trailing newline (similar to -n) |
| \0NNN | Character with octal value NNN |
| \xHH | Character with hex value HH |
Detailed Examples
Basic Text Output
The most fundamental use of echo is displaying simple text messages to the terminal.
# Display a simple message
echo Hello, World!
# Display a message with multiple words
echo This is a test message from the echo command
echo Hello World→ "Hello World" (spaces collapsed)echo "Hello World"→ "Hello World" (spaces preserved)
Displaying Shell Variables
Echo is commonly used to display the values of shell variables, which is essential for debugging and script output.
# Set some variables
USERNAME="craig"
SERVER="web01.binghamton.edu"
PORT=8080
# Display variable values
echo "Current user: $USERNAME"
echo "Server: $SERVER"
echo "Port: $PORT"
# Display environment variables
echo "Your home directory: $HOME"
echo "Current path: $PATH"
echo "Current shell: $SHELL"
$ before a variable name tells the shell to substitute the variable's value. This is one of echo's most common uses - showing what's stored in variables during script execution. Double quotes allow variable expansion, while single quotes would display the literal $USERNAME text.
${VARIABLE} with curly braces when the variable name needs to be separated from surrounding text: echo "File: ${NAME}_backup.tar"
Creating Files with Redirection
Echo combined with output redirection is a quick way to create files or add content to them.
# Create a new file with single line
echo "This is the first line" > newfile.txt
# Overwrite (be careful!)
echo "This replaces everything" > newfile.txt
# Append to file (safe)
echo "This is line 1" > myfile.txt
echo "This is line 2" >> myfile.txt
echo "This is line 3" >> myfile.txt
# Display the file
cat myfile.txt
> operator creates a new file (or overwrites an existing one) with echo's output. The >> operator appends to an existing file or creates it if it doesn't exist. This is extremely useful in scripts for creating configuration files, logging events, or building output files incrementally.
> will destroy existing file content without warning! Always use >> to append unless you specifically want to overwrite.
echo "$(date): Backup completed successfully" >> /var/log/backup.log
Using -n to Suppress Newline
The -n option prevents echo from adding a newline, keeping the cursor on the same line.
# Normal echo adds newline
echo "Processing file..."
echo "Done"
# Using -n to stay on same line
echo -n "Enter your name: "
read NAME
echo "Hello, $NAME!"
# Useful for progress indicators
echo -n "Starting backup..."
sleep 2
echo " Done!"
Escape Sequences with -e Option
The -e option enables special escape sequences for formatted output including newlines, tabs, and colors.
# Multiple lines with \n
echo -e "Line 1\nLine 2\nLine 3"
# Tabs for alignment with \t
echo -e "Name:\tCraig"
echo -e "Server:\tweb01"
echo -e "Status:\tActive"
# Combining escapes
echo -e "Header\n------\nItem 1\nItem 2\nItem 3"
# Bell/alert sound
echo -e "Warning!\a"
\n creates a newline (line break), \t creates a tab for alignment, and \a produces a system beep. This allows you to create formatted output in a single echo command instead of multiple separate echo statements.
\t for columnar output, but for precise alignment across varying data lengths, consider using the column or printf commands instead.
Color Output Using ANSI Escape Codes
Echo can display colored text using ANSI escape sequences, making script output more readable and visually organized.
# Define color codes
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color (reset)
# Display colored messages
echo -e "${RED}Error: File not found${NC}"
echo -e "${GREEN}Success: Operation completed${NC}"
echo -e "${YELLOW}Warning: Low disk space${NC}"
echo -e "${BLUE}Info: Starting backup process${NC}"
# Colored status messages
echo -e "${GREEN}[OK]${NC} Web server is running"
echo -e "${RED}[FAIL]${NC} Database connection failed"
echo -e "${YELLOW}[WARN]${NC} SSL certificate expires in 7 days"
\033[... sequences) control terminal colors and formatting. The format is \033[ followed by color codes and ending with m. Always reset with ${NC} (No Color) at the end to prevent color bleeding into subsequent output. This makes script output much more readable, with errors in red, successes in green, and warnings in yellow.
\033[0;30m- Black\033[0;31m- Red\033[0;32m- Green\033[0;33m- Yellow\033[0;34m- Blue\033[1;3Xm- Bold (bright) versions (X = color number)\033[0m- Reset to default
Command Substitution in Echo
Echo can display the output of other commands using command substitution, perfect for dynamic information.
# Display current date and time
echo "Current date and time: $(date)"
# Show system information
echo "Hostname: $(hostname)"
echo "Uptime: $(uptime -p)"
echo "Current user: $(whoami)"
# File and directory information
echo "Current directory: $(pwd)"
echo "Files in current directory: $(ls | wc -l)"
echo "Disk usage of /home: $(df -h /home | tail -1 | awk '{print $5}')"
# Process information
echo "Running processes: $(ps aux | wc -l)"
# Network information
echo "IP Address: $(hostname -I | awk '{print $1}')"
$(command) syntax runs the command and substitutes its output into the echo statement. This is incredibly powerful for creating dynamic messages that include real-time system information. The command inside $() is executed first, then its output replaces the $() portion in your echo statement.
`command`, but $(command) is preferred because it's easier to read and nest: $(command1 $(command2))
$(date +%Y-%m-%d)- ISO format date$(date +%H:%M:%S)- Current time$(whoami)@$(hostname)- user@host format$(cat /proc/cpuinfo | grep processor | wc -l)- CPU count
Generating CSV Data
Echo is useful for creating simple CSV (comma-separated values) files for data export or import.
# Create CSV header
echo "Hostname,IP Address,Status,Last Check" > servers.csv
# Add data rows
echo "web01,192.168.1.10,Online,2025-01-15" >> servers.csv
echo "web02,192.168.1.11,Online,2025-01-15" >> servers.csv
echo "db01,192.168.1.20,Offline,2025-01-15" >> servers.csv
echo "db02,192.168.1.21,Online,2025-01-15" >> servers.csv
# Generate CSV from variables
HOSTNAME=$(hostname)
IP=$(hostname -I | awk '{print $1}')
STATUS="Online"
DATE=$(date +%Y-%m-%d)
echo "$HOSTNAME,$IP,$STATUS,$DATE" >> servers.csv
# View the CSV
cat servers.csv
| or tab \t, or wrap fields in quotes: echo "\"$DATA1\",\"$DATA2\""
Script Debugging and Status Messages
Echo is essential for debugging scripts by displaying variable values and execution progress.
#!/bin/bash
# Backup script with debugging output
BACKUP_DIR="/backup"
SOURCE_DIR="/home/craig/documents"
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="backup_${DATE}.tar.gz"
echo "========================================="
echo "Starting Backup Process"
echo "========================================="
echo ""
echo "Configuration:"
echo " Source: $SOURCE_DIR"
echo " Destination: $BACKUP_DIR"
echo " Filename: $BACKUP_FILE"
echo ""
echo -n "Checking if source directory exists... "
if [ -d "$SOURCE_DIR" ]; then
echo "OK"
else
echo "FAILED"
echo "Error: Source directory not found: $SOURCE_DIR"
exit 1
fi
echo -n "Checking if backup directory exists... "
if [ -d "$BACKUP_DIR" ]; then
echo "OK"
else
echo "Creating backup directory..."
mkdir -p "$BACKUP_DIR"
fi
echo ""
echo "Creating backup archive..."
tar -czf "$BACKUP_DIR/$BACKUP_FILE" "$SOURCE_DIR" 2>&1
echo ""
echo "Backup completed: $BACKUP_DIR/$BACKUP_FILE"
echo "File size: $(du -h $BACKUP_DIR/$BACKUP_FILE | cut -f1)"
echo "========================================="
echo -n creates a professional-looking output with inline status indicators (OK/FAILED).
echo "[$(date +%H:%M:%S)] Starting process..." helps track how long each step takes.
Creating Multi-line Configuration Files
Using echo with escape sequences and redirection to create complex multi-line configuration files.
# Method 1: Multiple echo commands
echo "[database]" > config.ini
echo "host = localhost" >> config.ini
echo "port = 3306" >> config.ini
echo "user = admin" >> config.ini
echo "" >> config.ini
echo "[logging]" >> config.ini
echo "level = INFO" >> config.ini
echo "file = /var/log/app.log" >> config.ini
# Method 2: Single echo with -e and \n
echo -e "[database]\nhost = localhost\nport = 3306\nuser = admin\n\n[logging]\nlevel = INFO\nfile = /var/log/app.log" > config2.ini
# Method 3: Using variables for dynamic configuration
SERVER="192.168.1.100"
PORT="8080"
APP_NAME="WebApp"
echo -e "# $APP_NAME Configuration" > app.conf
echo -e "# Generated: $(date)\n" >> app.conf
echo -e "[server]" >> app.conf
echo -e "address = $SERVER" >> app.conf
echo -e "port = $PORT" >> app.conf
echo -e "max_connections = 100\n" >> app.conf
echo -e "[security]" >> app.conf
echo -e "ssl_enabled = true" >> app.conf
echo -e "cert_file = /etc/ssl/cert.pem" >> app.conf
# Display the generated file
cat app.conf
cat > file <<EOF ... EOF. It's often cleaner for large configuration files.
Additional Information
While echo is simpler, the printf command offers more precise formatting control:
# Echo (simple but less control)
echo "User: $USER Balance: $BALANCE"
# Printf (more control, like C's printf)
printf "User: %-10s Balance: %8.2f\n" "$USER" "$BALANCE"
Use echo for simple output, printf when you need specific formatting like decimal places, field widths, or padding.
- No quotes: Simple text without special characters:
echo Hello - Double quotes ("..."): When including variables or spaces:
echo "User: $USER" - Single quotes ('...'): When you want literal text (no variable expansion):
echo 'Cost: $5.00'
Echo behavior can vary between shells (bash, sh, zsh, etc.) and between built-in vs. external versions. For portable scripts, consider using printf instead, which has more consistent behavior across shells.
# Horizontal line separators
echo "========================================"
# Blank lines for spacing
echo ""
# Error messages to stderr
echo "Error: Operation failed" >&2
# Conditional messages
[ $? -eq 0 ] && echo "Success" || echo "Failed"
# Logging with timestamps
echo "[$(date +'%Y-%m-%d %H:%M:%S')] Event logged" >> /var/log/app.log
# Progress dots
for i in {1..5}; do echo -n "."; sleep 1; done; echo " Done!"
# Box drawing
echo "╔════════════════════╗"
echo "║ System Status ║"
echo "╚════════════════════╝"
- Not quoting variables:
echo $VARcan break with spaces. Useecho "$VAR" - Forgetting -e for escapes:
echo "Line1\nLine2"prints literally. Useecho -e - Using > instead of >>: Accidentally overwriting files. Be careful with redirectors!
- Not resetting colors: Forgetting
${NC}after ANSI codes bleeds color - Echo in command substitution: Usually unnecessary: use variables directly
In loops with many iterations, repeatedly appending with echo can be slow. For better performance, collect output in a variable or use a temporary file:
# Slow (many disk writes)
for i in {1..1000}; do
echo "Line $i" >> output.txt
done
# Faster (batch write)
OUTPUT=""
for i in {1..1000}; do
OUTPUT+="Line $i\n"
done
echo -e "$OUTPUT" > output.txt
Quick Reference Card
| Task | Command |
|---|---|
| Display text | echo "Hello World" |
| Display variable | echo "$VARIABLE" |
| No trailing newline | echo -n "text" |
| Enable escape sequences | echo -e "Line1\nLine2" |
| Create file | echo "content" > file.txt |
| Append to file | echo "content" >> file.txt |
| Command substitution | echo "Date: $(date)" |
| Color output | echo -e "\033[0;31mRed text\033[0m" |
| Error to stderr | echo "Error" >&2 |
| Blank line | echo "" or just echo |