Shell Scripting with Style - Arthur Dick

Friday, June 28th, 2024

Shell scripts are the workhorses of the Linux and Unix world. They automate tasks, manage files, and orchestrate complex workflows. But let's face it, plain text output can get monotonous. This is where ANSI escape codes come in, adding a splash of color and functionality to your scripts, making them more informative, user-friendly, and even entertaining.

What are ANSI Escape Codes?

ANSI escape codes are a set of special byte sequences that control the terminal display. They are embedded within the text stream and interpreted by the terminal emulator, not displayed as characters themselves. These codes can achieve various effects, including:

Benefits of Using ANSI Escape Codes

Enhanced Readability

Colored text grabs attention and improves comprehension. Imagine a script that identifies errors in red and successes in green. Suddenly, the output becomes self-explanatory, reducing the need for further analysis.

User-Friendly Prompts

Colorful prompts can guide users through interactive scripts. For example, a script might display a bright yellow prompt for confirmation before deleting files.

Progress Bars and Spinners

ANSI escape codes can be used to create basic progress bars or spinning indicators, keeping users informed about long-running tasks.

Custom Layouts

By strategically positioning text and using separators, you can create custom layouts for displaying complex information.

Portability

ANSI escape codes are widely supported by most terminal emulators, making your scripts function consistently across different environments.

Cheat Sheet

Basic Styles and Colors

Text Styles

Foreground Colors

Background Colors

Bright Foreground Colors

Bright Background Colors

Palette Colors (256 Colors)

Foreground and Background

{n} ranges from 0 to 255:

RGB Colors

Foreground and Background

{r}, {g}, and {b} are the red, green, and blue components (0-255).

Cursor Manipulation

Cursor Movement

Cursor Positioning

Cursor Visibility

Screen Manipulation

Clearing Screen

Alternate Screen

Example: Highlighting Errors

#!/bin/bash

# Function to print an error message in red
error_message() {
  echo -e "\033[31mError: $1\033[0m"
}

# Example usage
if [ ! -f "myfile.txt" ]; then
  error_message "File 'myfile.txt' does not exist!"
fi

Example: Progress Bar

#!/bin/bash

# Function to display a progress bar
draw_progress_bar() {
  local progress=$(( $1 * 10 / $2 ))
  local bar

  # Save cursor position before drawing
  echo -ne "\033[s"

  for i in {1..10}; do
    if [ $i -le $progress ]; then
      bar="#";
    else
      bar=" ";
    fi
    echo -ne "$bar"
  done

  # Restore cursor position after drawing
  echo -ne "\033[u"
}

# Simulate work with a loop
total_steps=10
draw_progress_bar 0 $total_steps

echo -e "Long running process:\033[?25l"
for i in $(seq 1 $total_steps); do
  # Simulate work (replace with your actual command)
  sleep 0.5

  # Update progress bar for each step
  draw_progress_bar $i $total_steps
done

echo -e "\nProcess completed.\033[?25h"

Remember

By incorporating ANSI escape codes, you can elevate your shell scripts from basic tools to user-friendly and informative experiences. So, unleash your inner script artist and start adding a splash of color to your shell scripting adventures!

Tags: shell scriptingcommand line

← The Little ThingsEmbracing Accessibility →