Printing Messages in Different Colors

In this tutorial, we’ll learn how to use the echo command to print messages in different colors using shell scripts. This is particularly useful for visually distinguishing between success, failure, and warning messages in your scripts.

Introduction to the echo Command

The echo command is used to print messages to the screen. With the -e option, we can enable the interpretation of backslash-escaped characters and use ANSI color codes to format the output.

Hello World Script with Colors

Let’s write a simple script to demonstrate how to use the echo command for printing messages in different colors.

Script

#!/bin/bash
# Print basic messages
echo "This is Gaurav Sharma"
echo 'This is our first                 shell script'

# Print colored messages
echo -e "\033[0;31m fail message here"
echo -e "\033[0;32m success message here"
echo -e "\033[0;33m warning message here"

Explanation

  1. echo:

    • Prints messages to the terminal.
    • Multiple spaces between words are ignored unless enclosed in quotes.
  2. \033:

    • Escape sequence for initiating color codes.
  3. Color Codes:

    • Red: \033[0;31m
    • Green: \033[0;32m
    • Yellow: \033[0;33m

Running the Script

Save the script as echo.sh and make it executable:

chmod +x echo.sh

Run the script:

┌──(gaurav㉿learning-ocean)-[~/shellscript-youtube]
└─$ ./echo.sh
This is Gaurav Sharma
This is our first                 shell script
fail message here
success message here
warning message here

Output

  1. Fail Message: Displays in red.
  2. Success Message: Displays in green.
  3. Warning Message: Displays in yellow.

Demo Video

For a detailed walkthrough, check out the Demo Video.


Conclusion

Using colored outputs in shell scripts enhances readability, especially for success, error, and warning messages. Experiment with different color codes to suit your needs and make your scripts more intuitive.

Stay tuned for the next tutorial, where we’ll explore adding comments to shell scripts.

For more tutorials, visit Learning Ocean. Happy scripting!