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?
Asked
Active
Viewed 2,636 times
1
-
To which OS are you referring ? It'll probably be different in Windows/Unix command lines. – Walter Stabosz Mar 30 '12 at 18:59
-
1possible duplicate of [How to animate the command line?](http://stackoverflow.com/questions/60221/how-to-animate-the-command-line) – Eric Petroelje Mar 30 '12 at 19:00
2 Answers
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