Bash Script Init Style Status Message


Have you ever wondered how the OK and/or FAILED messages are printed out in the initialization of services on a Linux system during bootup? Well… I have. Anyway, I’ve always thought that it was really cool how the OK and FAILED messages printed out at the same column on the screen and in different colors. So of course I wanted to know how to do that so I could use it in my own scripts.

The Source

If you look inside some of your systm init scripts you’ll notice that many of them source the /etc/rc.d/init.d/functions script. This is actually where I found the code to produce neato status messages.

The Code

I could have just sourced that file (included) in my scripts and been fine, but I wanted my scripts to be self-contained so I took the liberty of pulling out the applicable code. Here it is below with comments:

# Column number to place the status message
# Command to move out to the configured column number
MOVE_TO_COL="echo -en \\033[${RES_COL}G"
# Command to set the color to SUCCESS (Green)
SETCOLOR_SUCCESS="echo -en \\033[1;32m"
# Command to set the color to FAILED (Red)
SETCOLOR_FAILURE="echo -en \\033[1;31m"
# Command to set the color back to normal
SETCOLOR_NORMAL="echo -en \\033[0;39m"

# Function to print the SUCCESS status
echo_success() {
    echo -n "["
    echo -n $" OK "
    echo -n "]"
    echo -ne "\r"
    return 0

# Function to print the FAILED status message
echo_failure() {
    echo -n "["
    echo -n $"FAILED"
    echo -n "]"
    echo -ne "\r"
    return 1


So you can just drop the above at the top of your script and then call the appropriate functions where needed. For example you could do something like this:

echo -n "Checking file exists..."
if [ -e ${SOME_FILE} ]; then
# Now echo out a newline

Pretty simple, eh? Now what type of script might you need something like this in? Check out my previous article How To Create A Bash Install Script, which is a perfect example of the type of script in which you may want these status type messages.

Thanks for stopping by! I hope that you’ll leave any comments that you have below.