Class 17 of 37 • Shell Scripting Fundamentals \t\t\t\t

Echo Command in Linux Shell Scripting - Syntax, Options & Color Guide

The echo command is one of the most widely used built-in commands across Linux, Bash, and POSIX shells. It prints lines of text, variables, or formatted strings directly to the standard output (stdout), a terminal screen, or a file through I/O redirection.

Echo Options and Escape Characters

The table below details the essential command-line flags and backslash escape sequences supported by echo:

Sr.No

Option / Sequence

Descriptions

01

-n

Do not print the trailing newline (leaves cursor on the same line).

02

-e

Enable interpretation of backslash escape characters (such as \n and \t).

03

-E

Disable interpretation of backslash escapes (default behavior in Bash).

04

\b

Backspace: erases the preceding character.

05

\n

Newline: moves cursor to the beginning of the next line.

06

\t

Horizontal Tab: inserts standard tab spacing.

07

\v

Vertical Tab: moves down one line while preserving column position.

08

\r

Carriage Return: moves cursor back to the start of the line without advancing.

09

\c

Suppress further output from that point forward (omits newline).

10

\\

Prints a literal backslash character.

Practical Code Examples

1. Basic Output vs Output without Trailing Newline

#!/bin/bash
# Normal echo adds a newline at the end
echo "Welcome to Veewom Technology"

# Echo with -n leaves cursor at the prompt for user input
echo -n "Enter user password: "
read password

2. Using Escape Sequences with -e

#!/bin/bash
# IMPORTANT: Backslash escapes require the -e flag in Bash!
echo -e "Line 1: Linux Basics\nLine 2: Shell Scripting\nLine 3: Advanced C"

# Tab-separated columns
echo -e "ID\tNAME\tCOURSE\n101\tRahul\tBCA\n102\tPriya\tMCA"

Colored Terminal Output with ANSI Escape Codes

One of the most valuable capabilities of echo -e is formatting text with colors, bold fonts, and background highlights using ANSI escape sequences:

Color / Style

ANSI Code

Example Usage

Red (Errors)

\e[31m

echo -e "\e[31m[ERROR] Connection failed\e[0m"

Green (Success)

\e[32m

echo -e "\e[32m[SUCCESS] Build complete\e[0m"

Yellow (Warnings)

\e[33m

echo -e "\e[33m[WARNING] Low disk space\e[0m"

Blue (Info)

\e[34m

echo -e "\e[34m[INFO] Starting daemon...\e[0m"

Reset

\e[0m

Mandatory at the end to restore normal terminal text color!

Output Redirection with Echo

You can write or append string data directly into files or streams using shell redirection operators:

# Overwrite (truncate) file with string
echo "server_ip=192.168.1.100" > /tmp/config.conf

# Append new line to existing file
echo "port=8080" >> /tmp/config.conf

# Redirect message to Standard Error (stderr)
echo "Fatal: Invalid configuration file" >&2

echo vs printf

While echo is quick for simple terminal messages, professional scripts frequently employ the POSIX printf command because printf behavior is 100% identical across all Unix platforms, shells, and operating systems:

# printf uses C-style formatting without requiring -e
printf "User: %-10s | Score: %5d | Avg: %6.2f\n" "Rohan" 95 98.45

Lab Practice: Formatted & Colored Server Status Console

Problem: Write a shell script that checks system load and displays a formatted dashboard with colored alerts using echo -e.

#!/bin/bash
# server_dashboard.sh: Formatted status display

# Define color constants
RED='\e[31m'
GREEN='\e[32m'
YELLOW='\e[33m'
CYAN='\e[36m'
BOLD='\e[1m'
NC='\e[0m' # No Color / Reset

clear
echo -e "${BOLD}${CYAN}==================================================${NC}"
echo -e "${BOLD}${CYAN}        LINUX SERVER HEALTH MONITOR CONSOLE       ${NC}"
echo -e "${BOLD}${CYAN}==================================================${NC}"
echo -e "Hostname    : $(hostname)"
echo -e "Timestamp   : $(date)"
echo -e "Kernel Ver  : $(uname -r)"
echo -e "--------------------------------------------------"

# Simulate service checks
echo -e -n "Checking Web Server (Nginx)   ... "
echo -e "${GREEN}[RUNNING]${NC}"

echo -e -n "Checking Database (MySQL)     ... "
echo -e "${GREEN}[RUNNING]${NC}"

echo -e -n "Checking Firewall (UFW)       ... "
echo -e "${YELLOW}[ACTIVE - 4 Rules]${NC}"

echo -e -n "Checking Disk Free Space      ... "
free_space=$(df -h / | awk 'NR==2 {print $5}')
echo -e "${YELLOW}[${free_space} USED]${NC}"

echo -e "${BOLD}${CYAN}==================================================${NC}"

Frequently Asked Questions (FAQs)

Include the -e option to tell Bash to interpret backslash escapes: echo -e "First\nSecond". Without -e, Bash prints literal \n.
Use the -n option: echo -n "Enter username: ". The prompt remains on the same line so the user can type right next to it.
Use single greater-than > to overwrite the file (e.g. echo "text" > output.txt) or double greater-than >> to append to the end of the file.
echo is built into shells with minor variations between UNIX flavors (e.g. BSD vs GNU). printf follows the standard POSIX specification, allowing exact formatting precision (like %d, %s, and field widths) across all shells.

Next Step in Your Linux Learning Path:

Capture interactive user inputs, passwords, and file lines in Class 18: Read Command.

Continue to Class 18: Read Command → Previous: ← Variables | Full Syllabus

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!