Animated return status indicator for bash

Posted by Ryan Uber | Bourne-Again Shell (bash) | Wednesday 12 January 2011 1:34 am
#!/bin/bash
# File Name: inc.animexec.sh
# Author:    Ryan R. Uber <ryan@blankbmx.com>
#
# This function will provide an animated cursor while a process
# runs in the background. Upon the programs completion, the
# exit status will be reflected by the standard CentOS
# echo_success and echo_failure functions.
#
# Usage: animexec [commands here]
# Note:  If using output redirection, enclose your commands
#        in quotes so that the actual output of the status
#        messages do not get redirected.

. /etc/init.d/functions

function animexec()
{
    LOCKFILE=/tmp/.lock_${RANDOM}
    trap "rm -f ${LOCKFILE}; exit" INT TERM EXIT

    echo "" > ${LOCKFILE}
    ( /bin/bash -c "${@}"; echo $? > ${LOCKFILE} ) & 

    while /bin/true; do

        for C in ">     " \
                 "=>    " \
                 " =>   " \
                 "  =>  " \
                 "   => " \
                 "    =>" \
                 "     ="; do

            RESULT="$(cat ${LOCKFILE})"
            if [ -z "${RESULT}" ]; then
                ${MOVE_TO_COL}
                echo -n "[${C}]"
                sleep 0.1
            else
                rm -f ${LOCKFILE}
                if [ ${RESULT} -eq 0 ]; then
                    success
                    echo
                    return 0
                else
                    failure
                    echo
                    return 1
                fi
            fi

        done

    done

}

# = EXAMPLES ===================================
echo -en "6 second operation that returns true:"
animexec "/bin/sleep 6"

echo -en "2 second operation that returns true:"
animexec "/bin/sleep 2"

echo -en "6 second operation that returns false:"
animexec "/bin/sleep 6 && /bin/false"

echo -en "2 second operation that returns false:"
animexec "/bin/sleep 2 && /bin/false"

# EOF