How to build a colored script?

QuestionsQuestions8 SkillsProDec, 18 2025
096

Building a colored script is a fantastic way to apply what you've learned. In LabEx, you can use the built-in WebIDE (VSCode-like) or the Terminal to create this.

Let's build a simple "System Health" script that uses colors to make information stand out.

Step 1: Create the Script File

In your terminal, use nano (a simple text editor installed in your VM) to create a file:

nano health_check.sh

Step 2: Add the Code

Copy and paste the following code into the editor. This script uses variables to store tput styles, making the code much cleaner:

#!/bin/bash

# Define Colors and Styles
GREEN=$(tput setaf 2)
RED=$(tput setaf 1)
BOLD=$(tput bold)
RESET=$(tput sgr0)

# Clear the screen for a clean look
tput clear

echo "${BOLD}--- LabEx System Health Check ---${RESET}"
echo "---------------------------------"

# 1. Check if a directory exists
if [ -d "/home/labex/project" ]; then
    echo "Project Directory: ${GREEN}FOUND${RESET}"
else
    echo "Project Directory: ${RED}MISSING${RESET}"
fi

# 2. Check if a tool is installed (like htop which you installed earlier)
if command -v htop &> /dev/null; then
    echo "HTOP Tool:         ${GREEN}INSTALLED${RESET}"
else
    echo "HTOP Tool:         ${RED}NOT FOUND${RESET}"
fi

echo "---------------------------------"
echo "${BOLD}Done!${RESET}"

Step 3: Save and Exit

  1. Press Ctrl + O then Enter to save the file.
  2. Press Ctrl + X to exit the editor.

Step 4: Make it Executable and Run

In Linux, you must give a script "execute" permission before you can run it:

# Give execution permission
chmod +x health_check.sh

# Run the script
./health_check.sh

Why this is a "Learn By Doing" Milestone:

  • Variables: You practiced storing complex commands in simple names.
  • Automation: You moved from running single commands to a sequence of commands (a script).
  • Visual Feedback: You used tput to make the output immediately understandable (Green = Good, Red = Problem).

This project perfectly prepares you for the Challenges mentioned in the lab documentation! Challenges will often ask you to "Create a script that..." exactly like we just did.

Ready to wrap up? Click Continue to finish this lab and see your progress updated in the Skill Tree! 🌳✨

0 Comments

no data
Be the first to share your comment!