How to create a rotation animation using shell script?
Use that script:
#!/bin/bash
chars="/-\|"
while :; do
for (( i=0; i<${#chars}; i++ )); do
sleep 0.5
echo -en "${chars:$i:1}" "\r"
done
done
The while
loop runs infinite. The for
loop runs trough each character of the string given in $chars
. echo
prints the character, with a carriage return \r
, but without linebreak -n
. -e
forces echo to interpret escape sequences such as \r
.
There's a delay of 0.5 seconds between each change.
Here's an example using \b
, which tells the terminal emulator to move the cursor one column to the left, in order to keep overwriting the same character over and over.
#!/usr/bin/env bash
spinner() {
local i sp n
sp='/-\|'
n=${#sp}
printf ' '
while sleep 0.1; do
printf "%s\b" "${sp:i++%n:1}"
done
}
printf 'Doing important work '
spinner &
sleep 10 # sleeping for 10 seconds is important work
kill "$!" # kill the spinner
printf '\n'
See BashFAQ 34 for more.