Creating a Bash Spinner

 in

Do you know what this sequence of characters "/-\|/-\|" is for? A text based spinner. Still confused, read on.

You've probably seen some long running console program that shows a spinner while it runs. A spinner being the aforementioned sequence of characters output one after the other at the same place on the screen with a pause between each character. The code in this article creates a spinner which runs in a separate process. By doing this the spinner spins at a constant rate and doesn't pause when your script pauses. It also eliminates the need to sprinkle spinner output messages throughout your program.

In addition the spinner reads from a log file created by the main process and displays the last line from the log file next to the spinner. When the log file goes away the spinner exits.

This is the script for the main process, called runner.sh:

#!/bin/bash

logfile=/tmp/mylog

echo >$logfile
trap "rm -f $logfile" EXIT

# Output message to log file.
function log_msg()
{
    echo "$*" >>$logfile
}


# Start spinner
sh spinner.sh &

# Perform really long task.
i=0
log_msg "Starting a really long job"
while [[ $i -lt 100 ]]
do
    sleep 1
    let i+=5
    log_msg "$i% complete"
done

sleep 1
echo

The function at the top is to output a message to the log file. The log file is initialized to an empty file at the top of the program and the output function appends to it.

Before entering its main loop, the main process starts the spinner in the background. After that it just pauses a bit, outputs a status message and then repeats till it's 100% complete.

The spinner process follows:

#!/bin/bash

logfile=/tmp/mylog
logsize=0
spinpause=0.10
linelen=0


# Output last line from log file.
function lastout()
{
    local line=$(tail -n 1 $logfile 2>/dev/null)
    if [[ "$line" ]]; then
        echo -n "     $line"

        # Erase any extra from last line.
        local len
        let len=$linelen-${#line}
        while [[ $len -gt 0 ]]
        do
            echo -n " "
            let len--
        done
        linelen=${#line}
    fi
}

# Output a spin character.
function spinout()
{
    local spinchar="$1"
    local sz
    local ll
    if [[ -f $logfile ]]; then
        echo -n -e "\r$spinchar"
        sleep $spinpause

        # Check for new message.
        sz=$(stat --printf '%s' $logfile 2>/dev/null)
        if [[ $sz -gt $logsize ]]; then
            lastout
            logsize=$sz
        fi
    fi
}

if [[ -f $logfile ]]; then
    logsize=$(stat --printf '%s' $logfile 2>/dev/null)
    if [[ $logsize -gt 0 ]]; then
        echo -n " "
        lastout
    fi

    while [[ -f $logfile ]]
    do
        spinout "/"
        spinout "-"
        spinout "\\"
        spinout "|"
        spinout "/"
        spinout "-"
        spinout "\\"
        spinout "|"
    done
    echo
fi

The spinner contains two functions. The first function outputs the last line from the log file. Since the log file line is always placed on the same screen line it's possible that the new log line is shorter than the last log line. So, after outputting the new line the function outputs spaces up to the length of the previous log line so that it is completely erased.

The second function outputs a spinner character and pauses for the inter-character pause time. It precedes the spinner character with a carriage return so that everything remains on the same line. After outputting the spinner character it checks to see if the log file has grown in size since the last time it output a line. If it has, it then outputs a new line.

The main loop of the spinner outputs each of the spinner characters, one after the other.

Watch the attached video the see it run.

AttachmentSize
spinner.mp41.05 MB
spinner.ogv1.55 MB
______________________

Mitch Frazier is an Associate Editor for Linux Journal.

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

redundancy

Anonymous's picture

is there a reason why you print two identical sets of the characters instead of just one (

/-\|

)?

Just Goofy I Guess

Mitch Frazier's picture

Nope, it's not necessary. I guess I just starting rotating the spinner image in my brain to count the positions and never noticed when the characters actually repeated.

Mitch Frazier is an Associate Editor for Linux Journal.

Here's my 'spin' on this tip :)

Anonymous's picture

Here's one I wrote a while ago. It basically puts the twirly characters in a string and cuts the "next" character in the animation sequence. The term "twirly" is coined by my then-3yr-old ;)

I can't get the "code" HTML tag to properly format this code block. If someone at LJ can make it pretty like Mitch's, that would be most appreciated ;).

#!/bin/bash
shopt -s xpg_echo

twirl() {
    tc="`echo $twirlstr | cut -c$j`"
    col=$1
    [[ "${tc}" == "\\" ]] && echo "${esc}[${col}G\\${tc}\c"
    [[ "${tc}" == "\\" ]] || echo "${esc}[${col}G${tc}\c"

    [[ $j -eq 5 ]] || ((j++))
    [[ j -eq 5 ]] && j=1
}

twirlstr="-\|/"
declare -i j=1
esc="\\033"

echo "This is a twirly example:"
for (( i=1 ; i < 100 ; i++ ))
do
    echo "${esc}[0GDoing stuff...............................\c" #"

    # Print the next twirly character at colume 45
    twirl 45

    # lines of code to "do stuff"

done
echo "\n"

Of course, this is just a sample...the "for" loop would realistically be something more like a "while" or some such thing. This scriplet uses ANSI VTxxx escape sequences to place the cursor.

Preeeeeeeeeeee

Mitch Frazier's picture

That would be <pre>...</pre>, I guess we have droopy set to filter out <code> tags.

Fixed.

Thanks for the twirly!

Mitch Frazier is an Associate Editor for Linux Journal.

Let me re-phrase that

Mitch Frazier's picture

Apparently <code> tags aren't filtered out, they just don't seem to work correctly. Oh webmaster...

Mitch Frazier is an Associate Editor for Linux Journal.

Another Correction

Jeff Rasmussen's picture

I wasn't able to get the 2 scripts to work until I changed the call in runner.sh

From:
sh spinner.sh &

To:
bash spinner.sh &

Default shell

Mitch Frazier's picture

Your default shell must not be bash. Probably better to make spinner.sh executable and execute it via

./spinner.sh &

Just make sure that the copy of spinner.sh that you have doesn't have the typo referred to in the comment below.

Mitch Frazier is an Associate Editor for Linux Journal.

Minor typo

samba's picture

FYI, just a small typo...

The second code section starts with:

#!/bin/basn

Great article though! I look forward to using this in my code!

Fixed

Mitch Frazier's picture

Thanks.

Mitch Frazier is an Associate Editor for Linux Journal.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState