1

I often see a spinning animation in the command prompt/shell consisting of -, /, and \. This type of printing, which simply overwrites whatever is already there, is also used to show progress in downloading stuff with command line applications. How is this done?

Nate Glenn
  • 6,455
  • 8
  • 52
  • 95

2 Answers2

4

Usually this is done by printing a backspace character (ASCII code 8) and then the next character in the sequence. In most programming languages you can just use \b in a string for this.

For example, here is some Python code for this:

import time
import sys
sys.stdout.write(' ')
while True:
    for c in ('/', '-', '\\', '|'):
        time.sleep(1)
        sys.stdout.write('\b' + c)
        sys.stdout.flush()
Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
1

As mentioned, you can usually use a backspace char, \b to do it. Here's a simple example for bash (since you didn't specify a platform, I picked one ;) ):

#!/bin/bash

spin_states=(- \\ \| /)

function spin {
    echo -n "Working...  "
    for ((i=0; i<$1; i++))
    do
        state=$((i % ${#spin_states[@]}))
        echo -ne "\b${spin_states[state]}"
        sleep .1 # A "real" script would probably do something useful here
    done
    echo
}

spin 100
FatalError
  • 52,695
  • 14
  • 99
  • 116